# leetCode 34.Search for a Range (搜索范围) 解题思路和方法

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;
}
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：leetCode 34.Search for a Range (搜索范围) 解题思路和方法 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)