题目描述:(链接)
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]
.
解题思路:
二分查找
1 class Solution { 2 public: 3 vector<int> searchRange(vector<int>& nums, int target) { 4 vector<int> result; 5 int len = nums.size(); 6 int first = 0; 7 int last = len - 1; 8 while (first <= last) { 9 int mid = first + (last - first) / 2; 10 if (nums[mid] == target) { 11 int l1 = mid; 12 int l2 = mid; 13 while (--l1 >= 0 && nums[l1] == target); 14 while (++l2 < len && nums[l2] == target); 15 result.push_back(++l1); 16 result.push_back(--l2); 17 break; 18 } else if (target < nums[mid]) { 19 last = mid - 1; 20 } else { 21 first = mid + 1; 22 } 23 } 24 25 if (result.size() == 0) { 26 result.push_back(-1); 27 result.push_back(-1); 28 } 29 30 return result; 31 } 32 };