题目描述:
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].
这里用了二分法的思想。
如果value比数组的最大值大,比最小值小,那么就直接返回[-1, -1]。
如果数组都是同一个数且等于value,就直接返回[0,n-1]。(n为数组长度)
如果数组的最左边等于value,则从左往右寻找有多少个等于value的值
如果数组的最右边等于value,则从右往左寻找有多少个等于value的值
否则就看nums[mid],其中mid=(left+right)/2。如果nums[mid]等于value,就从中间向两边寻找等于value的值,如果nums[mid]小于value,那么value肯定在数组的右边,如果nums[mid]大于value,那么value肯定在数组的左边。
public class Solution {
public int[] searchRange(int[] nums, int target) {
int n=nums.length;
int[] a=new int[]{-1,-1};
if(n==0)
return a;
int[] result=search(nums, 0, n-1, target);
return result;
}
public int[] search(int[] nums,int left,int right,int target){
int[] a=new int[]{-1,-1};
if(target>nums[right]||target<nums[left]){
}else if(nums[left]==nums[right]){
a[0]=left;a[1]=right;
}else if(nums[left]==target&&nums[right]!=target){
int index=left+1;
while(nums[index]==target){
index++;
}
a[0]=left;a[1]=index-1;
}else if(nums[right]==target&&nums[left]!=target){
int index=right-1;
while(nums[index]==target){
index--;
}
a[0]=index+1;a[1]=right;
}else{
int mid=(left+right)/2;
if(nums[mid]==target){
int i=mid-1;
int j=mid+1;
while(nums[i]==target){
i--;
}
while(nums[j]==target){
j++;
}
a[0]=i+1;a[1]=j-1;
}else if(nums[mid]<target){
return search(nums, mid+1, right, target); //这里不能是(nums, mid, right, target)
}else if(nums[mid]>target){
return search(nums, left, mid, target);
}
}
return a;
}
}