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 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].

Analyse: binary search. 

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         vector<int> range = {-1, -1};
 5         int left = 0, right = nums.size() - 1;
 6         while (left <= right) {
 7             int mid = left + (right - left) / 2;
 8             if (nums[mid] > target) right = mid - 1;
 9             else if (nums[mid] < target) left = mid + 1;
10             else {
11                 int start = mid, end = mid;
12                 while (start >= 0 && nums[start] == nums[mid]) start--;
13                 while (end < nums.size() && nums[end] == nums[mid]) end++;
14                 range[0] = start + 1;
15                 range[1] = end - 1;
16                 break;
17             }
18         }
19         return range;
20     }
21 };
原文地址:https://www.cnblogs.com/amazingzoe/p/5883719.html