Golang排序包中的BinarySearch

问题描述 投票:0回答:1

我正在查看 golang

sort
func SearchInts(a []int, x int) int
中的函数,并且很好奇是否有一种直接的方法来识别切片中是否存在元素?

在 Java Arrays.binarySearch(..) 中,仅返回负值。我很好奇 golang 的 api

func SearchInts(a []int, x int)
是否报告 x 不存在?不确定为什么
func SearchInts(a []int, x int)
不返回两个值
(index,isPresent)

algorithm api sorting go binary-search
1个回答
0
投票

您可以简单地检查:

i := sort.SearchInts(slice, value)
if i<len(slice) && slice[i]==value {
   // It exists
}
© www.soinside.com 2019 - 2024. All rights reserved.