@@ -52,7 +52,7 @@ edit_url: https://github.com/doocs/leetcode/edit/main/lcof/%E9%9D%A2%E8%AF%95%E9
52
52
53
53
由于数组 ` nums ` 已排好序,我们可以使用二分查找的方法找到数组中第一个大于等于 ` target ` 的元素的下标 $l$,以及第一个大于 ` target ` 的元素的下标 $r$,那么 ` target ` 的个数就是 $r - l$。
54
54
55
- 时间复杂度 $O(\log n)$,空间复杂度 $O(1)$。其中 $n$ 为数组的长度 。
55
+ 时间复杂度 $O(\log n)$,其中 $n$ 为数组的长度。 空间复杂度 $O(1)$。
56
56
57
57
<!-- tabs:start -->
58
58
@@ -70,13 +70,16 @@ class Solution:
70
70
71
71
``` java
72
72
class Solution {
73
+ private int [] nums;
74
+
73
75
public int search (int [] nums , int target ) {
74
- int l = lowerBound(nums, target);
75
- int r = lowerBound(nums, target + 1 );
76
+ this . nums = nums;
77
+ int l = search(target);
78
+ int r = search(target + 1 );
76
79
return r - l;
77
80
}
78
81
79
- private int lowerBound ( int [] nums , int x ) {
82
+ private int search ( int x ) {
80
83
int l = 0 , r = nums. length;
81
84
while (l < r) {
82
85
int mid = (l + r) >>> 1 ;
@@ -108,8 +111,8 @@ public:
108
111
109
112
```go
110
113
func search(nums []int, target int) int {
111
- l := sort.Search(len( nums), func(i int) bool { return nums[i] >= target } )
112
- r := sort.Search(len( nums), func(i int) bool { return nums[i] > target } )
114
+ l := sort.SearchInts( nums, target)
115
+ r := sort.SearchInts( nums, target+1 )
113
116
return r - l
114
117
}
115
118
```
0 commit comments