LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置
作者:互联网
34. 在排序数组中查找元素的第一个和最后一个位置
思路:
与AcWing 789一致
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
if (nums.size() == 0) return {-1, -1};
int begin, end;
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + r >> 1;
if (nums[mid] >= target) r = mid;
else l = mid + 1;
}
if (nums[l] != target) return {-1, -1};
else {
begin = l;
int l = 0, r = nums.size() - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (nums[mid] <= target) l = mid;
else r = mid - 1;
}
end = l;
}
return {begin, end};
}
};
标签:begin,target,nums,int,mid,34,查找,LeetCode,size 来源: https://www.cnblogs.com/hjy94wo/p/16613824.html