leetcode 34. 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]
思路:二分
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 vector<int> v(2, -1); 5 int l = 0, r = nums.size() - 1; 6 while (l < r) { 7 int mid = ((r - l) >> 1) + l; 8 if (nums[mid] >= target) //尽可能向左靠 9 r = mid; 10 else 11 l = mid + 1; 12 } 13 if (r < 0 || nums[l] != target) 14 return v; 15 v[0] = l; 16 r = nums.size() - 1; 17 while (l < r) { 18 int mid = ((r - l) >> 1) + l + 1; //偏向于右边 19 if (nums[mid] <= target) //尽可能向右靠 20 l = mid; 21 else 22 r = mid - 1; 23 } 24 v[1] = l; 25 return v; 26 } 27 };
越努力,越幸运