前往:如果唯一则追加 [英] Go: Append if unique

查看:91
本文介绍了前往:如果唯一则追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以检查切片/地图中是否存在值?

Is there a way to check slices/maps for the presence of a value?

我想在切片中添加一个值 如果切片中确实存在 ,则仅

I would like to add a value to a slice only if it does not exist in the slice.

这有效,但似乎很冗长。有没有更好的方法?

This works, but it seems verbose. Is there a beter way to do this?

orgSlice := []int{1, 2, 3}
newSlice := []int{}
newInt := 2

newSlice = append(newSlice, newInt)
for _, v := range orgSlice {
    if v != newInt {
        newSlice = append(newSlice, v)
    }
}

newSlice == [2 1 3]


推荐答案

您的方法每次插入都会花费线性时间。更好的方法是使用 map [int] struct {} 。另外,您也可以使用 map [int] bool 或类似的方法,但是空的 struct {} 具有优点是它不占用任何额外空间。因此 map [int] struct {} 是一组整数的常用选择。

Your approach would take linear time for each insertion. A better way would be to use a map[int]struct{}. Alternatively, you could also use a map[int]bool or something similar, but the empty struct{} has the advantage that it doesn't occupy any additional space. Therefore map[int]struct{} is a popular choice for a set of integers.

示例:

set := make(map[int]struct{})
set[1] = struct{}{}
set[2] = struct{}{}
set[1] = struct{}{}
// ...

for key := range(set) {
  fmt.Println(key)
}
// each value will be printed only once, in no particular order


// you can use the ,ok idiom to check for existing keys
if _, ok := set[1]; ok {
  fmt.Println("element found")
} else {
  fmt.Println("element not found")
}

这篇关于前往:如果唯一则追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆