您的位置:首页 > 其它

Leetcode 34. Search for a Range

2017-01-27 07:55 387 查看
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].

s思路:

1. 简单但不粗暴的做法:用lower_bound和upper_bound两个函数即可!

2. 肯定是要调用两次binary search来找到左右两个边界点!第一次,找比target小的最大值的位置;第二次找比target大的最小值的位置。这两个位置如果存在,则是求的范围!

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
//

int left=0,right=nums.size()-1;
vector<int> res{-1,-1};
if(nums.empty()) return res;
//第一次binary search,找左边边界
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>=target){
right=mid-1;
}else
left=mid+1;
}
if(left>=nums.size()||nums[left]!=target) return res;
//不厌其烦的说:对left是计算出来的,就要只带保护,即:先确定是否left在范围内!!
res[0]=left;
//第二次binary search,找右边边界!
right=nums.size()-1;
while(left<=right){
int mid=left+(right-left)/2;
if(nums[mid]>target){
right=mid-1;
}else
left=mid+1;
}
res[1]=right;
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode binarysear