Search for a Range
Posted amazingzoe
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 };
以上是关于Search for a Range的主要内容,如果未能解决你的问题,请参考以下文章