您的位置:首页 > 其它

leetcode-Search for a Range

2015-11-09 23:08 274 查看
Difficulty: Medium
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]
.


class Solution {
int my_lowerBound(vector<int> &nums,int target){
int left =0;
int right=nums.size()-1;

while(left<=right){
int mid=left+(right-left)/2;

if(nums[mid]==target){
if(mid==0||nums[mid-1]!=target)
return mid;
else
right=mid-1;
}
else if(nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
return -1;
}
int my_upperBound(vector<int> &nums,int target){
int left =0;
int size=nums.size();
int right=size-1;
while(left<=right){
int mid=left+(right-left)/2;

if(nums[mid]==target){
if(mid==size-1||nums[mid+1]!=target)
return mid;
else
left=mid+1;
}
else if(nums[mid]>target)
right=mid-1;
else
left=mid+1;
}
return -1;
}
public:
vector<int> searchRange(vector<int>& nums, int target) {

return {my_lowerBound(nums,target),my_upperBound(nums,target)};
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: