[LeetCode] 34. Search for a Range

Given an array of integers 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

 1 //better one from discuss, qp use l, r
 2 class Solution {
 3 public:
 4     vector<int> searchRange(vector<int>& nums, int target) {
 5         vector<int> ret(2, -1);
 6         int n = nums.size();
 7         int l = 0;
 8         int r = n - 1;
 9         int mid;
10         
11         while (l < r){
12             mid = (l+r) /2;
13             if (target > nums[mid]) l = mid + 1;
14             else if (target <= nums[mid]) r = mid;
15             //else r = mid; // push to left
16         }
17         
18         if (nums[l] != target) return ret;
19         else ret[0] = l;
20         
21         r = n - 1; // no need to reinit l;
22         while (l < r){
23             /*  !!!! make the r biasd to right */
24             mid = (l+r+1) / 2;
25             if (target < nums[mid]) r = mid - 1;
26             else if (target >= nums[mid]) l = mid;
27             //else l = mid; // move to right
28         }
29         
30         ret[1] = l;
31         
32         return ret;
33     }
34 };
原文地址:https://www.cnblogs.com/amadis/p/6707979.html