Created
May 27, 2014 11:58
-
-
Save johnwesonga/0004dfafa522de85eee2 to your computer and use it in GitHub Desktop.
Remove duplicate values from a slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
//O(n^2) time | |
func RemoveDuplicates(data []string) []string { | |
length := len(data) - 1 | |
for i := 0; i < length; i++ { | |
for j := i + 1; j <= length; j++ { | |
if data[i] == data[j] { | |
data[j] = data[length] | |
data = data[0:length] | |
length-- | |
j-- | |
} | |
} | |
} | |
return data | |
} | |
//O(n) | |
func ClearDuplicates(s []string) []string { | |
found := make(map[string]bool) | |
r := []string{} | |
for _, v := range s { | |
if _, ok := found[v]; !ok { | |
r = append(r, v) | |
found[v] = true | |
} | |
} | |
return r | |
} | |
func main() { | |
s := []string{"a", "john", "z", "b", "peter", "p", "a", "king", "k", "l", "k"} | |
fmt.Println(ClearDuplicates(s)) | |
fmt.Println(RemoveDuplicates(s)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment