LeetCode 34. Search for a Range
题目来源:https://leetcode.com/problems/search-for-a-range/description/
Given an array of integers sorted in ascending order, 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]
.
方法1:
public int[] searchRange(int[] nums, int target) {
int j=0;
int len=nums.length;
int []res=new int[]{-1,-1};
if(nums==null||len==0)
return res;
int l=0,r=len-1,mid=0;
while(l<=r){
mid=(l+r)/2;
if(nums[mid]==target){
break;
}
else if(nums[mid]<target)
l=mid+1;
else {
r=mid-1;
}
} //先找到一个target,然后寻找其左右边界。
if(nums[mid]!=target)
return res; //若找不到,则直接返回
int l1=0,r1=mid; //寻找左边界
while(l1<=r1){
int mid1=(l1+r1)/2;
if(nums[mid1]==target){
r1=mid1-1;
}
else{
l1=mid1+1;
}
}
int l2=mid,r2=len-1; //寻找右边界
while(l2<=r2){
int mid2=(l2+r2)/2;
if(nums[mid2]==target)
l2=mid2+1;
else{
r2=mid2-1;
}
}
res[0]=l1;
res[1]=r2;
return res;
}
/*使用三次二分法,先找到其中一个target以此为中心,向两边扩散找到左右边界,此种方法容易理解。可以优化为两次,但是我没有理解如何优化为两次
* */
方法二:
public int[] searchRange(int[] nums, int target) {
int []res=new int[]{-1,-1};
int left=0;
int right=nums.length-1;
while(left<=right){
int mid=(left+right)/2;
if(nums[mid]==target){
if(nums[left]==target&&nums[right]==target){
return new int[]{left,right};
}
else if(nums[left]!=target){
left++;
}
else {
right--;
}
}
else if(nums[mid]>target){
right=mid-1;
}
else{
left=mid+1;
}
}
return new int[]{-1,-1};
} //由两边向中间逐渐缩小范围,确定包含目标数字的下标范围