# Search for a Range

Oct 11, 2017

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].

vector<int> searchRange1(vector<int>& nums, int target) {
int first = 0,last = nums.size() - 1,mid;
vector<int> ret{-1,-1};
while(first <= last) {
mid = (first + last)/2;
if (nums[mid] == target){
break;
}
else if (nums[mid] < target) first = mid+1;
else last = mid - 1;
}

int l = mid,f = mid;
ret[0] = first;
ret[1] = last;

while(first <= l) {
int m = (first + l)/2;
if (nums[m] == nums[mid])
l = m - 1;
else if (nums[m+1] != nums[mid]) first = m + 1;
else {
ret[0] = m+1;
break;
}
}
while(f <= last) {
int m = (f + last)/2;
if (nums[m] == nums[mid]) f = m + 1;
else if (nums[m-1] != nums[mid]) last = m - 1;
else {
ret[1] = m - 1;
break;
}
}

return ret;
}


• 如果查找失败， 那么说明当前mid就是左边界
• 如果找到了，我们就更新mid，再对nums[0:mid-1]进行查找，直到查找失败。

vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ret{-1,-1};
int mid = nums.size();
while( (mid = searchRangeIter(nums,0,mid-1,target) ) != -1)
ret[0] = mid;
//mid = -1;
while( (mid = searchRangeIter(nums,mid+1,nums.size() - 1,target)) != -1)
ret[1] = mid;
return ret;
}
int searchRangeIter(vector<int> nums,int first,int last,int target) {
while(first <= last) {
int mid = (first + last)/2;
if (nums[mid] == target){
return mid;
}
else if (nums[mid] < target) first = mid+1;
else last = mid - 1;
}
return -1;
}


dicuss中看到一个更简洁的迭代的方法：

vector<int> searchRange(int A[], int n, int target) {
int i = 0, j = n - 1;
vector<int> ret(2, -1);
// Search for the left one
while (i < j)
{
int mid = (i + j) /2;
if (A[mid] < target) i = mid + 1;
else j = mid;
}
if (A[i]!=target) return ret;
else ret[0] = i;

// Search for the right one
j = n-1;  // We don't have to set i to 0 the second time.
while (i < j)
{
int mid = (i + j) /2 + 1;// Make mid biased to the right
if (A[mid] > target) j = mid - 1;
else i = mid;// So that this won't make the search range stuck.
}
ret[1] = j;
return ret;
}

LeetCodeLeetCode查找

Combination-Sum

Next-Permutation