1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
| // @Title: 在排序数组中查找数字 I (在排序数组中查找数字 LCOF)
// @Author: 15816537946@163.com
// @Date: 2022-02-03 11:38:36
// @Runtime: 4 ms
// @Memory: 3.8 MB
func search(nums []int, target int) int {
if len(nums) == 0 {
return 0
}
if len(nums) ==1 && target == nums[0] {
return 1
}
lo,hi := 0, len(nums)-1
index :=-1
for lo <= hi {
i := (lo+hi) >> 1
if nums[i] == target {
index = i
break
} else if nums[i] > target {
hi = i-1
} else {
lo = i+1
}
}
fmt.Println(index)
if index == -1 {
return 0
}
cnt :=0
for i:=index;i>=0 && nums[i]== target;i-- {
cnt++
}
for i:= index;i<len(nums) && nums[i]== target;i++ {
cnt++
}
return cnt-1
}
|