Total Accepted: 62397
Total Submissions: 225032
Difficulty: Medium
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
Subscribe to see which companies asked this question
这个题目还是二分查找的变形,首先要找到一个mid使得nums[mid]==targer,从而左右再用二分查找开始寻找,
public class Solution {
public int[] searchRange(int[] nums, int target) {
int [] result = new int[2];
result[0]=-1;result[1]=-1;
int head = 0;int tail = nums.length-1;
while(head<=tail){
int mid = head+(tail-head)/2;
if(nums[mid]==target){
int i=head;int j = mid;
while(i<j){
int mid1 = i+(j-i)/2;
if(nums[mid1]<target){
i=mid1+1;
}
else{
if(j==mid1)break;
j=mid1;
}
}
result[0]=j;
i=mid;j=tail;
while(i<j){
if(nums[j]==target){
i=j;
break;
}
int mid1 = i+(j-i)/2;
if(nums[mid1]>target){
j=mid1-1;
}
else{
if(i==mid1){
break;
}
i=mid1;
}
}
result[1]=i;
return result;
}
else{
if(nums[mid]>target){
tail=mid-1;
}
else{
head=mid+1;
}
}
}
return result;
}
}