-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchRange34.java
More file actions
35 lines (30 loc) · 939 Bytes
/
Copy pathsearchRange34.java
File metadata and controls
35 lines (30 loc) · 939 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
32
public class searchRange34 {
public int[] searchRange(int[] nums,int target){
int[] res=new int[]{-1,-1};
//左边界
res[0]=binarySearch(nums,target,true);
res[1]=binarySearch(nums,target,false);
return res;
}
//leftOrRight为true找左边界 false找右边界
public int binarySearch(int[] nums, int target, boolean leftOrRight) {
int res = -1;
int left = 0, right = nums.length - 1, mid;
while(left <= right) {
mid = left + (right - left) / 2;
if(target < nums[mid])
right = mid - 1;
else if(target > nums[mid])
left = mid + 1;
else {
res = mid;
//处理target == nums[mid]
if(leftOrRight)
right = mid - 1;
else
left = mid + 1;
}
}
return res;
}
}