Skip to content

Commit 9870992

Browse files
committed
add another solution of Binary Search
1 parent 8f95f9b commit 9870992

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

go/binary_search.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
//lint:file-ignore U1000 Ignore all unused code
22
package main
33

4+
import "sort"
5+
46
func binarySearchHalfClosed(nums []int, target int) int {
57
left, right := 0, len(nums)
68
for left < right {
@@ -32,3 +34,13 @@ func binarySearchClosed(nums []int, target int) int {
3234
}
3335
return -1
3436
}
37+
38+
func search(nums []int, target int) int {
39+
index := sort.Search(len(nums), func(i int) bool {
40+
return nums[i] >= target
41+
})
42+
if index < len(nums) && nums[index] == target {
43+
return index
44+
}
45+
return -1
46+
}

0 commit comments

Comments
 (0)