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

题意:找出已排序数组中指定元素的起止位置。

思路:因为要求时间复杂度为O(logn),所以用二分法

  1.利用二分法确定指定元素的起始位置,同时确定该数组中是否存在该元素

  2.利用二分法确定元素的终止位置

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