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]
.
题意:给定一个排序数组,有重复元素。给定一个target,在数组中找到target的其实位置和结束位置
要求时间复杂度为O(logn)
如果target不在数组中,返回[-1,1];
分类:数组,二分法
解法1:二分查找找到target所在位置。然后从该位置开始,向两边查找边缘。
public class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res = new int[2];
if(nums.length==0) return new int[]{-1,-1};
int low = 0;
int high = nums.length-1;
int mid = 0;
while(low<=high){
mid = (low+high)/2;
if(nums[mid]==target) break;
else if(nums[mid]>target) high = mid-1;
else low = mid+1;
}
if(nums[mid]==target){
int i = mid-1;
while(i>=0 && nums[i]==target){
i--;
}
if(nums[i+1]==target)
res[0] = i+1;
else
res[0] = mid;
i = mid+1;
while(i<nums.length&&nums[i]==target){
i++;
}
if(nums[i-1]==target)
res[1] = i-1;
else
res[1] = mid;
return res;
}else{
return new int[]{-1,-1};
}
}
}