LeetCode34-在排序数组中查找元素的第一个和最后一个位置
34. 在排序数组中查找元素的第一个和最后一个位置:
给定一个按照升序排列的整数数组 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 <= 10^5
- -10^9 <= nums[i] <= 10^9
- nums 是一个非递减数组
- -10^9 <= target <= 10^9
解题思路1:
二分,用STL的lower_bound和upper_bound可以。
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int x=lower_bound(nums.begin(),nums.end(),target)-nums.begin();
if(x==nums.size() || nums[x]!=target)
return {-1,-1};
int y=upper_bound(nums.begin(),nums.end(),target)-nums.begin();
return {x,y-1};
}
};
解题思路2:
手写二分。
class Solution {
int low_binary_search(const vector<int>& a,int target) {
int len=a.size();
int l=0,r=len;
while(l<r) {
int mid=(l+r)>>1;
if(a[mid]>=target)
r=mid;
else
l=mid+1;
}
return l;
}
int high_binary_search(const vector<int>& a,int target) {
int len=a.size();
int l=0,r=len;
while(l<r) {
int mid=(l+r)>>1;
if(a[mid]<=target)
l=mid+1;
else
r=mid;
}
return l;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {
int x=low_binary_search(nums,target);
if(x==nums.size() || nums[x]!=target)
return {-1,-1};
int y=high_binary_search(nums,target);
return {x,y-1};
}
};