Given an array of integers nums 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].
Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]class Solution {
public:
int FirstTarget(vector<int>& nums, int start, int end, int target)
{
while(start<=end)
{
int mid = start + (end-start)/2;
if(nums[mid] == target)
{
if(mid>0&&nums[mid-1]!=target || mid == 0)
return mid;
else
end = mid - 1;
}
else if(nums[mid]>target)
{
end = mid - 1;
}
else if(nums[mid]<target)
{
start = mid+1;
}
}
return -1;
}
int LastTarget(vector<int> &nums, int start, int end, int target)
{
if(start>end)
return -1;
int mid = start + (end-start)/2;
if(nums[mid] == target)
{
if(mid<nums.size()-1&&nums[mid+1]!=target || mid == end )
return mid;
else
start = mid + 1;
}
else if(nums[mid]>target)
{
end = mid - 1;
}
else if(nums[mid]<target)
{
start = mid+1;
}
return LastTarget(nums, start, end, target);
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> empty;
empty.push_back(-1);
empty.push_back(-1);
if(!nums.size())
return empty;
int firstidx = FirstTarget(nums, 0, nums.size()-1, target);
cout<<firstidx<<endl;
int lastidx = LastTarget(nums, 0, nums.size()-1, target);
cout<<lastidx<<endl;
vector<int> res;
res.push_back(firstidx);
res.push_back(lastidx);
return res;
}
};
本文介绍了一种在有序整数数组中查找指定目标值起始和结束位置的方法。算法采用二分查找策略实现 O(log n) 的时间复杂度。通过两个自定义函数分别定位目标值的第一个和最后一个出现位置。
3236

被折叠的 条评论
为什么被折叠?



