LeetCode 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].
给定一个有序数组和一个目标值,查找出目标值在数组中出现的发生下标区域。时间复杂度要求log(N)。
解法
刚开始以为下标也需要用二分来查找,但看讨论发现大家都是找出目标值然后再向两边搜索-_-b,这样做的话,最差的情况下(数组里的数全都一样)就是O(N)了,但是也能过。
class Solution
{
public:
vector<int> searchRange(vector<int>& nums, int target)
{
int left = 0;
int right = nums.size() - 1;
int index_a = -1;
int index_b = -1;
int index = 0;
bool flag = false;
while(left <= right)
{
int mid = (left + right) >> 1;
if(nums[mid] == target)
{
flag = true;
index = mid;
break;
}
else
if(nums[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
if(flag)
index_a = index;
while(index_a >= 1 && nums[index_a - 1] == target)
index_a --;
if(flag)
index_b = index;
while(index_b < nums.size() - 1 && nums[index_b + 1] == target)
index_b ++;
vector<int> rt = {index_a,index_b};
return rt;
}
};