您的位置:首页 > 其它

LeetCode 之 Search for a Range

2016-05-09 13:22 525 查看
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]
.

有序数组中的查找,使用二分查找,由于是要查重复元素的上下边界,所以要不止一次的二分查找,根据网上一篇博文的思路是用两次二分查找分别找到左右边界,需要注意到:在寻找左边界时,low要一直寻找target元素,在寻找右边界时,low遇到target要向右移动,直到不等于target。代码如下:

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> ans={-1,-1};
int length=nums.size();
if(length==0) return ans;
int llow=0,lhigh=length-1;
while(llow<=lhigh){
int mid=(llow+lhigh)/2;
if(nums[mid]<target)
llow=mid+1;
else
lhigh=mid-1;
}
int rlow=0,rhigh=length-1;
while(rlow<=rhigh){
int mid=(rlow+rhigh)/2;
if(nums[mid]<=target)
rlow=mid+1;
else
rhigh=mid-1;
}
if(llow<=rhigh){
ans[0]=llow;
ans[1]=rhigh;
}
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: