Home  >  Article  >  Backend Development  >  How to remove duplicates from slices in golang

How to remove duplicates from slices in golang

(*-*)浩
(*-*)浩Original
2019-12-28 09:55:533851browse

How to remove duplicates from slices in golang

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn