[JAVA]
看到题目要求时间复杂度为O(log n) 即考察二分查找,
对于sorted array:
只需要定义左边界left,右边界right,中点mid=left+(right-left)/2,
while(left<=right){
if(target==mid) return mid;
if target在左边[left,mid),则right=mid-1,重新开始二分查找;
else 即target在右边(mid,right],则left=mid+1,重新开始二分查找;
}
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
要分别查找target的左边界和右边界,实现两个方法:
1.searchRightIndex()
2.searchLeftIndex()
class Solution {
public int[] searchRange(int[] nums, int target) {
int[] res={-1,-1};
int right=searchRightIndex(nums,0,nums.length-1,target);
if(right<0||nums[right]!=target)
return res;
res[0]=searchLeftIndex(nums,0,right,target);
res[1]=right;
return res;
}
public int searchRightIndex(int[] nums,int left,int right,int target){
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target) right=mid-1;
else left=mid+1;
}
return right;
}
public int searchLeftIndex(int[] nums,int left,int right,int target){
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]<target) left=mid+1;
else right=mid-1;
}
return left;
}
}
//https://blog.csdn.net/happyaaaaaaaaaaa/article/details/50846000