34. Search for a Range
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]
.
方法一、暴力查找时间复杂度为O(n)
方法二、二分查找法,时间复杂度为O(lgn)
未改进前的代码--找到最左边得而target的位置和最有边为target的位置
int findLeftLoc(vector<int>& nums, int low, int high, int target)
{
while(low <= high)
{
int mid = low + (high - low) / 2;
if(nums[mid] == target)
{
if(mid == 0)
return mid;
if(nums[mid - 1] != target)
return mid;
else
high = mid - 1;
}
else if(nums[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int findRightLoc(vector<int>& nums, int low, int high, int target)
{
while(low <= high)
{
int mid = low + (high - low) / 2;
if(nums[mid] == target)
{
if(mid == high)
return mid;
if(nums[mid + 1] != target)
return mid;
else
low = mid + 1;
}
else if(nums[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
vector<int> searchRange(vector<int>& nums, int target) {//二分查找时间复杂度为O(logN)
vector<int> result(2,-1);
int low = 0;
int high = nums.size() - 1;
if(low <= high)
{
result[0] = findLeftLoc(nums,low,high,target);
result[1] = findRightLoc(nums,low,high,target);
}
return result;
}
改进后的代码:
vector<int> searchRange(vector<int>& nums, int target) {//二分查找时间复杂度为O(logN)
vector<int> result(2,-1);
int low = 0;
int high = nums.size() - 1;
if(nums.size() <= 0)
return result;
//找到最左边的等于target的元素的下标
while(low < high)
{
int mid = low + (high - low) / 2;
if(nums[mid] < target)
low = mid + 1;
else
high = mid;
}
if(nums[low] != target)
return result;
else
result[0] = low;
//找到最右边的等于target的元素的下标
high = nums.size() - 1;
while(low < high)
{
int mid = low + (high - low) / 2 + 1;
if(nums[mid] > target)
high = mid - 1;
else
low = mid;
}
result[1] = high;
return result;
}