Search for a Range
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].
思路:此题在思考的时候走了些弯路,一心想着一个循环解决这个问题。可是写代码的时候总是不能非常好的解出。最后突然想起来。全然能够先二分查找最低的位置。然后再查找最高位置就可以,这样就非常easy了。只是里面还是有一些细节须要注意。
详细代码例如以下:
public class Solution { public int[] searchRange(int[] nums, int target) { int[] ans = new int[]{-1,-1}; //排除特殊情况 if(nums.length == 0 || nums[0] > target || nums[nums.length-1] < target) return ans; //首尾都相等 if(nums[0]== target && nums[nums.length-1] == target){ ans[0] = 0; ans[1] = nums.length - 1; return ans; } //二分查找 int low = 0; int hight = nums.length - 1; int mid = 0; //先求符合要求的起始值 while(low <= hight){ mid = (low + hight)/2; if(nums[mid] > target){ hight = mid -1; }else if(nums[mid] < target){ low = mid + 1; }else{ hight = mid; }//推断结束情况 if(mid > 0 && nums[mid] == target && nums[mid -1] < target){ break; }else if(mid == 0 && nums[mid] == target){ break; } } //是否须要赋值。假设最低位置不存在,那么最高位置也不存在 if(nums[mid] == target){ ans[0] = mid; //再求符合要求的最大位置 low = mid;//起始值设为target的最低位置 hight = nums.length - 1; while(low <= hight){ mid = (low + hight)/2; if(mid < nums.length - 1 && nums[mid + 1] == target){ mid ++;//这里非常关键,由于(low+hight)/2自己主动向下取整的,所以看情况+1或向上取整 } //分情况更新位置 if(nums[mid] > target){ hight = mid -1; }else if(nums[mid] < target){ low = mid + 1; }else{ low = mid; } //推断最高位置 if(mid <nums.length-1 && nums[mid] == target && nums[mid +1] > target){ break; }else if(mid == nums.length-1 && nums[mid] == target){ break; } } ans[1] = mid;//最低位存在。最高位肯定也存在 } return ans; } }