标签:
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 int n=nums.size(),low=0,high=n-1,mid; 5 vector<int> res; 6 while(low<=high){ 7 mid=low+(high-low)/2; 8 if(nums[mid]<target){ 9 low=mid+1; 10 } 11 else{ 12 high=mid-1; 13 } 14 } 15 if(nums[low]==target){ 16 res.push_back(low); 17 while(low<n&&nums[low]==target) low++; 18 res.push_back(low-1); 19 } 20 else{ 21 res.push_back(-1); 22 res.push_back(-1); 23 } 24 return res; 25 } 26 };
Leetcode 34. Search for a Range
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/5699667.html