Skip to content

Instantly share code, notes, and snippets.

@arehmandev
Created October 3, 2017 15:00
Show Gist options
  • Save arehmandev/4790544bf08f9965596eb0d75f9f270b to your computer and use it in GitHub Desktop.
Save arehmandev/4790544bf08f9965596eb0d75f9f270b to your computer and use it in GitHub Desktop.
Remove duplicates in a slice
func removeDuplicates(elements []string) []string { // change string to int here if required
// Use map to record duplicates as we find them.
encountered := map[string]bool{} // change string to int here if required
result := []string{} // change string to int here if required
for v := range elements {
if encountered[elements[v]] == true {
// Do not add duplicate.
} else {
// Record this element as an encountered element.
encountered[elements[v]] = true
// Append to result slice.
result = append(result, elements[v])
}
}
// Return the new slice.
return result
}
// usage: removeDuplicates(slice)
@zhuzaiye
Copy link

zhuzaiye commented May 16, 2020

//Non - in - place modification, output to duplicate results and duplicates
func RemoveDuplicates2(s []string) ([]string, []string){
	//使用map[string]struct{}进行记录重复项,空的struct{}节省内存
	encountered := make(map[string]struct{})
	result := make([]string, 0)  //make初始化slice,必须给定长度
	duplicate := make([]string, 0)
	for _, v := range s {
		if _, ok := encountered[v]; ok{
			duplicate = append(duplicate, v)  //append是否比slice[index]更快
			continue
		}else {
			encountered[v] = struct{}{}
			result = append(result, v)
		}
	}
	return result, duplicate
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment