-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution53-1.java
More file actions
31 lines (30 loc) · 915 Bytes
/
Solution53-1.java
File metadata and controls
31 lines (30 loc) · 915 Bytes
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
class Solution {
public int search(int[] nums, int target) {
// 搜索右边界 right
int i = 0, j = nums.length - 1;
while (i <= j) {
int m = (i + j) / 2;
if (nums[m] <= target)
i = m + 1;
else
j = m - 1;
}
int right = i;
// 若数组中无 target ,则提前返回
if (j >= 0 && nums[j] != target)
return 0;
// 搜索左边界 right
i = 0;
j = nums.length - 1;
while (i <= j) {
int m = (i + j) / 2;
if (nums[m] < target)
i = m + 1;
else
j = m - 1;
}
int left = j;
return right - left - 1;
}
}
// 链接:https://leetcode-cn.com/problems/zai-pai-xu-shu-zu-zhong-cha-zhao-shu-zi-lcof/solution/mian-shi-ti-53-i-zai-pai-xu-shu-zu-zhong-cha-zha-5/