英文:
sort.Search, looking for a number that is not in the slice
问题
我目前在我的项目中遇到一个问题,我必须找到在一个切片中不存在的数字。我在golang网站上找到了可行的代码,这个代码很好用。在我的项目中,我创建了一个空块,让else语句完成所有的工作。我试图修改代码以删除空块,但每次都出现错误,最后我找到了一个能重现问题的示例:
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
nr := 9
sort.Ints(data)
index := sort.Search(len(data), func(index int) bool { return data[index] == nr })
if index == len(data) {
fmt.Print("It's not in : ")
fmt.Println(nr)
} else {
fmt.Print("It's in! Index is at : ")
fmt.Println(index)
}
}
在golang playground上可以运行这段代码!
英文:
I currently have a problem in my project where i must find numbers that are not present in a slice. I found working code in the golang website, this works great. In my project i make a empty block and let the else statement do all the work. I tried to alter the code to remove the empty block but i got errors every time, i finaly found a example that reproduces the problem :
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
nr := 9
sort.Ints(data)
index := sort.Search(len(data), func(index int) bool { return data[index] == nr })
if index == len(data) {
fmt.Print("It's not in : ")
fmt.Println(nr)
} else {
fmt.Print("It's in! Index is at : ")
fmt.Println(index)
}
}
Working code on golang playground!
答案1
得分: 5
我也遇到了同样的问题,因为我误解了godoc sort Search
中的文档。
> 如果调用者想要查找23是否在切片中,它必须单独测试data[i] == 23
。
我以为这意味着“文档说==
是允许的”。实际上,在作为参数传递给sort.Search
函数时,只能使用>=
或<=
,不能使用==
。而那句话的意思是,在你得到索引i
之后,你必须用data[i] == 23
来测试,以确保23在切片中。
英文:
I encounter the same problem too, because I misunderstood the document in godoc sort Search
.
> If the caller wants to find whether 23 is in the slice, it must test data[i] == 23 separately.
I thought that means "The documentation says that == is allowed" too. In fact, in the function as a parameter in sort.Search, can only use >=
or <=
, no ==
. And that sentence means after you got the index i
, you have to test it with data[i] == 23
to make sure 23 is in the slice.
答案2
得分: 3
例如,
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
sort.Ints(data)
fmt.Println(data)
x := 9
notpresent := false
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i >= len(data) || data[i] != x {
// x不在data中,
// 但i是它将被插入的索引。
notpresent = true
}
fmt.Println(x, notpresent)
}
输出:
[4 8 9 12 15 17 19 21 23 25 27]
9 false
英文:
For example,
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{27, 15, 8, 9, 12, 4, 17, 19, 21, 23, 25}
sort.Ints(data)
fmt.Println(data)
x := 9
notpresent := false
i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
if i >= len(data) || data[i] != x {
// x is not present in data,
// but i is the index where it would be inserted.
notpresent = true
}
fmt.Println(x, notpresent)
}
Output:
[4 8 9 12 15 17 19 21 23 25 27]
9 false
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论