leetcode 34. Find First and Last Position of Element in Sorted Array【裸二分】
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
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:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int>ans;
int l = 0, r = nums.size() - 1;
if (r == -1){//不可以再忘记边界了!!!
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
while (l < r) {
int mid = (l + r) >> 1;
if (nums[mid] >= target)
r = mid;
else
l = mid + 1;
}
if (nums[r] != target)
ans.push_back(-1);
else
ans.push_back(r);
l = 0, r = nums.size() - 1;
while (l < r) {
int mid = (l + r + 1) >> 1;//求小于等于或者小于某target通用的,因为是上限
if (nums[mid] <= target)
l = mid;
else
r = mid - 1;
}
if (nums[l] != target)
ans.push_back(-1);
else
ans.push_back(l);
return ans;
}
};