LeetCode34: Search for a Range
Given a sorted array of integers, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the orderO(LogN).
If the target is not found in the array, return[-1, -1]
.
For example,
Given[5, 7, 7, 8, 8, 10]
And target value 8,
Return[3, 4]
.
Subscribe to see which companies asked this question
// Question requirement: Give a sorted array, find the first position of the target and the last position of the target, and find the first position of the target, index1, respectively, and the position where the target finally appears, index2 // subtract 1 from the position where (target + 1) appears for the first time to obtain the position class Solution {public: vector
SearchRange (vector
& Nums, int target) {int index1 = lower_bound (nums, target); int index2 = lower_bound (nums, target + 1)-1; // use (target + 1) subtract 1 from the first position to obtain the final position of the target if (index1 <nums. size () & nums [index1] = target) return {index1, index2}; else return {-1,-1 };} int lower_bound (vector
& Nums, int target) {int left = 0, right = nums. size ()-1; while (left <= right) {int mid = (right + left)/2; if (nums [mid] <target) left = mid + 1; else right = mid-1 ;}return left ;}};