duanjiuhong5843 2014-10-23 00:24
浏览 32
已采纳

搜索,查找不在切片中的数字

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!

  • 写回答

2条回答 默认 最新

  • doubo4336 2014-10-23 01:28
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度