Search for a Range
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].
思路:此题在思考的时候走了些弯路,一心想着一个循环解决问题,但是写代码的时候总是不能很好的解出。最后突然想起来,完全可以先二分查找最低的位置,然后再查找最高位置即可,这样就很简单了。不过里面还是有一些细节需要注意。
具体代码如下:
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; } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-12 19:53:18