Merge two integer slices and return a slice without duplicate elements. There are two deduplication strategies
1. Pass Double loop to filter duplicate elements (time is exchanged for space) (recommended learning: go)
// 通过两重循环过滤重复元素 func RemoveRepByLoop(slc []int) []int { result := []int{} // 存放结果 for i := range slc{ flag := true for j := range result{ if slc[i] == result[j] { flag = false // 存在重复元素,标识为false break } } if flag { // 标识为false,不添加进结果 result = append(result, slc[i]) } } return result }
2. Filter through dictionary (space is exchanged for time)
Because the primary key of the dictionary is unique, it can be used to determine whether elements are repeated
// 通过map主键唯一的特性过滤重复元素 func RemoveRepByMap(slc []int) []int { result := []int{} tempMap := map[int]byte{} // 存放不重复主键 for _, e := range slc{ l := len(tempMap) tempMap[e] = 0 if len(tempMap) != l{ // 加入map后,map长度变化,则元素不重复 result = append(result, e) } } return result }
ps: In order to save memory, map[int]byte is used here. Because the value of map is not used, any type can be used.
The above is the detailed content of How to remove duplicates from slices in golang. For more information, please follow other related articles on the PHP Chinese website!