-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchRange.java
More file actions
38 lines (34 loc) · 928 Bytes
/
SearchRange.java
File metadata and controls
38 lines (34 loc) · 928 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
33
34
35
36
37
38
/**
* 34 在排序数组中查找元素的第一个和最后一个位置
*/
public class SearchRange {
public int[] searchRange(int[] nums, int target) {
int[] res = {-1, -1};
int left=0, right=nums.length-1;
int mid;
while (left<right){
mid = (left+right)/2;
if(nums[mid]==target){
left = mid;
break;
}
if(nums[mid]<target){
left = mid+1;
}else{
right=mid;
}
}
if(left<nums.length && nums[left]==target) {
right = left;
while (left >= 0 && nums[left] == target) {
left--;
}
while (right < nums.length && nums[right] == target) {
right++;
}
res[0] = left + 1;
res[1] = right - 1;
}
return res;
}
}