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]
.
转自 点击打开链接
这题想了很久,就算后来看了别人的解答,对于参数nums.length和nums.length-1和 start<end,还是想不太明白。首先分析一下searchStart函数中,while条件start<end,不能写成start<=end, 当start和end相等,则nums[middle]==target, end=middle,searchStart函数就会进入死循环。所以start不能等于end。
而在searchRange函数中调用searchStart函数时,如果写nums.length-1,当nums只有一个元素时,searchStart函数中while循环条件不成立,返回的是start,若nums中元素正好是要查找的元素,则result[0] =start,result[1] =start-1,不满足。所以写nums.length可以保证此情况下进入while循环,保证start是target在nums中的下标或要插入的位置。
class Solution {
public int[] searchRange(int[] nums, int target) {
int [] result={-1,-1};
if(nums==null || nums.length==0)
return result;
else {
result[0]=searchStart(nums,0,nums.length,target);
if(result[0] >= nums.length || nums[result[0]]!=target){ //不存在
return new int [] {-1,-1};
}
result[1]=searchStart(nums,0,nums.length,target+1)-1;
}
return result;
}
public int searchStart(int[] nums,int start,int end,int target){
int middle=(end+start)/2;
while(start<end){
middle = (end+start)/2;
if(nums[middle]<target){
start=middle+1;
}else{
end=middle;
}
}
return start;
}
}