Android大法好！！

###### 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 范围搜寻 解题报告

2016-04-06 10:35:34

#### leetcode Combination Sum解题报告

2015-10-22 18:20:59

#### 【LeetCode-面试算法经典-Java实现】【034-Search for a Range（搜索一个范围）】

2015-07-27 07:17:03

#### LeetCode解题报告--Search for a Range

2015-12-04 13:32:03

#### Leetcode解题思路总结(Easy)

2015-12-17 17:12:03

#### Leetcode解题思路总结(Medium)

2016-02-15 15:37:14

#### LeetCode 34.Search for a Range

2015-02-17 12:00:30

#### [leetcode] 34.Search for a Range

2015-08-26 23:40:28

#### leetcode - 34.Search for a Range

2017-03-02 19:57:52

#### [Leetcode]34.Search for a Range

2016-03-10 21:57:56

## 不良信息举报

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