golang之sort.Strings和sort.SearchStrings

需求:查询string是否在[]string中存在

var a string

var list []string

原有解决办法:先使用sort.Strings(list)排序,然后判断sort.SearchStrings(list,a)的值是否为-1

测试案例1:如果list为nil,sort.SearchStrings(list,a)为0, 与a的值无关

测试案例2:如果list有值且长度不为空,先使用sort.Strings(list)排序

a存在与list中-->sort.SearchStrings(list,a)为a在list中的索引

a不存在list中-->sort.SearchStrings(list,a)值会随着a的值变化而变化

我们来看下文档

---from dash

 

a不存在list中-->sort.SearchStrings(list,a)值会随着a的值变化而变化 这种情况与文档的描述

if x is not present (it could be len(a))不符

 

 

查看sort.SearchStrings的实现过程:

```json
func Search(n int, f func(int) bool) int {
// Define f(-1) == false and f(n) == true.
// Invariant: f(i-1) == false, f(j) == true.
i, j := 0, n
for i < j {
h := i + (j-i)/2 // avoid overflow when computing h
// i ≤ h < j
if !f(h) {
i = h + 1 // preserves f(i-1) == false
} else {
j = h // preserves f(j) == true
}
}
// i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
return i
}

// Convenience wrappers for common cases.

// SearchInts searches for x in a sorted slice of ints and returns the index
// as specified by Search. The return value is the index to insert x if x is
// not present (it could be len(a)).
// The slice must be sorted in ascending order.
//
func SearchInts(a []int, x int) int {
return Search(len(a), func(i int) bool { return a[i] >= x })
}
```

其实这就是一个二分查找来判定所属的位置。

经过sort.Strings(list)排序后,sort.SearchStrings总结如下:

1、如果找到,返回a在list中的索引

2、如果没找到,返回a在list中的索引(即把a放入list中排序后,在list中的索引)

 

转载于:https://www.cnblogs.com/Mike-Feng/p/6894000.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值