leetcode34 - Find First and Last Position of Element in Sorted Array - medium
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]
Constraints:
0 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
nums
is a non decreasing array.-10^9 <= target <= 10^9
用sheep的模板,找start pos的话是模板2-r总是返回true,找end pos是模板1-l总是返回true。
找到start pos后要check一下此时nums[r]是否是target,不是的话就是找不到。
开始找end pos时把r更新回array尾端,l其实不用改,end pos至少也和此时的l相等。
实现:O(logn)
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { vector<int> res{-1, -1}; if (nums.empty()) return res; int l = 0, r = nums.size()-1; while (l < r){ int m = l + (long long)r >> 1; if (nums[m] >= target){ r = m; }else{ l = m+1; } } if (nums[r] != target) return res; res[0] = r; r = nums.size()-1; while (l < r){ int m = l + (long long)r + 1 >> 1; if (nums[m] <= target){ l = m; }else{ r = m-1; } } res[1] = l; return res; } };