[LeetCode] Search for a Range
The idea is to search for the left and right boundaries of target via two binary searches. Well, some tricks may be needed. Take a look at this link :-)
The code is rewritten as follows.
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 int l = left(nums, target); 5 if (l == -1) return {-1, -1}; 6 return {l, right(nums, target)}; 7 } 8 private: 9 int left(vector<int>& nums, int target) { 10 int n = nums.size(), l = 0, r = n - 1; 11 while (l < r) { 12 int m = l + ((r - l) >> 1); 13 if (nums[m] < target) l = m + 1; 14 else r = m; 15 } 16 return nums[l] == target ? l : -1; 17 } 18 int right(vector<int>& nums, int target) { 19 int n = nums.size(), l = 0, r = n - 1; 20 while (l < r) { 21 int m = l + ((r - l + 1) >> 1); 22 if (nums[m] > target) r = m - 1; 23 else l = m; 24 } 25 return r; 26 } 27 };