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中的索引)

 

posted @ 2017-05-23 14:34  小峰峯  阅读(2858)  评论(0编辑  收藏  举报