给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。
如果数组中不存在目标值 target,返回 [-1, -1]。
进阶:
你可以设计并实现时间复杂度为 O(log n) 的算法解决此问题吗?
示例 1:
输入:nums = [5,7,7,8,8,10], target = 8
输出:[3,4]
示例 2:
输入:nums = [5,7,7,8,8,10], target = 6
输出:[-1,-1]
示例 3:
输入:nums = [], target = 0
输出:[-1,-1]
提示:
0 <= nums.length <= 105
-109 <= nums[i] <= 109
nums 是一个非递减数组
-109 <= target <= 109
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result{-1, -1};
for(int i = 0, j = nums.size() - 1; i <= j; )
{
if(nums[i] > target || nums[j] < target)
{
return result;
}
if(nums[i] == target && result[0] == -1)
{
result[0] = i;
result[1] = i;
for( ; i < j; )
{
if(nums[j] == target)
{
result[1] = j;
break;
}
if(nums[i+1] > target)
{
result[1] = i;
break;
}
int k = (i+j)/2;
if(nums[k] > target)
{
j = k;
}
else
{
i = k;
}
}
return result;
}
if(nums[j] == target && result[1] == -1)
{
result[1] = j;
result[0] = j;
for( ; i < j; )
{
if(nums[i+1] == target)
{
result[0] = i+1;
break;
}
int k = (i+j)/2;
if(nums[k] < target)
{
i = k;
}
else
{
j = k;
}
}
return result;
}
if(i == j)
{
break;
}
int k = (i+j)/2;
if(nums[k] > target)
{
i++;
j = k - 1;
}
else if(nums[k] < target)
{
i = k+1;
j--;
}
else if(nums[k] == target)
{
int m = k;
for( ; i < m; )
{
if(nums[m-1] < target)
{
break;
}
int _m = (m+i)/2;
if(nums[_m] < target)
{
i = _m;
}
else
{
m = _m;
}
}
result[0] = m;
m = k;
for( ; m < j; )
{
if(nums[m+1] > target)
{
break;
}
int _m = (m+j)/2;
if(nums[_m] > target)
{
j = _m;
}
else
{
m = _m;
}
}
result[1] = m;
return result;
}
}
return result;
}
};