考虑以下示例:
package main
import (
"fmt"
"sort"
)
func main() {
var n int
var a sort.IntSlice
a = append(a, 23)
a = append(a, 3)
a = append(a, 10)
sort.Sort(a)
fmt.Println(a)
n = sort.SearchInts(a, 1)
fmt.Println(n)
n = sort.SearchInts(a, 3)
fmt.Println(n)
}
http://play.golang.org/p/wo4r43Zghv
结果是:
[3 10 23]
0
0
当第一个元素和不存在的元素都返回 0 作为索引时,我应该如何知道 slice 中是否存在数字?
更新 请注意,索引也可以大于 slice 的长度,因此查找 slice 中是否存在元素的正确方法是:
num := 1
n = sort.SearchInts(a, num)
if n < len(a) && a[n] == num {
// found
}
最佳答案
这可能看起来是一个功能上奇怪的特性,但它被记录在案:
For instance, given a slice data sorted in ascending order, the call Search(len(data), func(i int) bool { return data[i] >= 23 }) returns the smallest index i such that data[i] >= 23.
明显的解决方案也记录在案:
If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.
关于go - sort.SearchInts 工作异常或者我遗漏了一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14436751/