- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
假设您有两个用例:
a := [] int {2, 2, 3, 4}
i := sort.Search(len(a), func(pos int) bool { return a[pos] == 2})
fmt.Printf("%v -> %v \n", a, i)
b := [] int {1, 2, 2, 3, 4}
j := sort.Search(len(b), func(pos int) bool { return b[pos] == 2})
fmt.Printf("%v -> %v \n", b, j)
答案是:
[2 2 3 4] -> 4
[1 2 2 3 4] -> 1
我想在这两种情况下它都必须是 1
,不是吗?有谁知道为什么吗?
最佳答案
sort.Search()
返回 [0, n)
中 f(i)
为 true
的最小索引 i
。
由于 slice 索引是从 0 开始的,因此您应该期望第一个返回 0
,第二个返回 1
。它(似乎)适用于第二个。
引用文档:
...assuming that on the range [0, n),
f(i) == true
impliesf(i+1) == true
. That is, Search requires thatf
isfalse
for some (possibly empty) prefix of the input range [0, n) and thentrue
for the (possibly empty) remainder; Search returns the firsttrue
index. If there is no such index, Search returnsn
.
您的函数不符合 sort.Search()
期望的条件。您的功能不是判断指定索引处的元素是否是您要查找的元素,而是告诉:
true
)false
)。(如果您只判断它们何时相等而不判断它们何时大于或小于,则无法进行二分查找。)
所以简单地使用>=
比较而不是==
。正确用法:
a := []int{2, 2, 3, 4}
i := sort.Search(len(a), func(pos int) bool { return a[pos] >= 2 })
fmt.Printf("%v -> %v \n", a, i)
b := []int{1, 2, 2, 3, 4}
j := sort.Search(len(b), func(pos int) bool { return b[pos] >= 2 })
fmt.Printf("%v -> %v \n", b, j)
输出(在 Go Playground 上尝试):
[2 2 3 4] -> 0
[1 2 2 3 4] -> 1
注意:同样来自文档:
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 thatdata[i] >= 23
. If the caller wants to find whether23
is in the slice, it must testdata[i] == 23
separately.
sort.SearchInts()
如果您想在 int
slice ([]int
) 中搜索 int
值,只需使用 sort.SearchInts()
:
a := []int{2, 2, 3, 4}
i := sort.SearchInts(a, 2)
fmt.Printf("%v -> %v \n", a, i)
b := []int{1, 2, 2, 3, 4}
j := sort.SearchInts(b, 2)
fmt.Printf("%v -> %v \n", b, j)
输出(在 Go Playground 上尝试):
[2 2 3 4] -> 0
[1 2 2 3 4] -> 1
关于search - 去二分查找错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33999844/
我正在尝试编写一个程序,在名为 items 的数组中进行顺序搜索和二分搜索,该数组具有 10000 个已排序的随机 int 值。第二个名为 targets 的数组加载了 1000 个 int 值(50
当我尝试使用图表并为其编写一些代码但没有成功时,我遇到了一个问题:/!! 我想创建一些东西来获取图形数据并检查它是否:1- 连接2-二分法3-有循环4-是一棵树 所以我想知道,例如,是否可以将其写入以
我是一名优秀的程序员,十分优秀!