leetcode笔记:34. Search for a Range
2017-02-17 11:09
363 查看
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
For example,
Given
return
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size();
vector<int> ans;
if(n==0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
int left1=0,right1=n,left2=0,right2=n;
int left,right;
int mid1,mid2;
while(left1<right1){
mid1=(left1+right1)/2;
if(target<=nums[mid1]){
right1=mid1;
}
else{
left1=mid1+1;
}
}
//cout<<left1<<endl;
//cout<<right1<<endl;
if(right1>=n||nums[right1]!=target){
left=-1;
}
else{
left=left1;
}
while(left2<right2){
mid2=(left2+right2)/2;
if(target>=nums[mid2]){
left2=mid2+1;
}
else{
right2=mid2;
}
}
//cout<<left2<<endl;
//cout<<right2<<endl;
if(right2-1>=n||nums[right2-1]!=target){
right=-1;
}
else{
right=right2-1;
}
ans.push_back(left);
ans.push_back(right);
return ans;
}
};
道理很简单,求左边界,相等就往左,最后停留在左边第一个target点。右边界,相等就往右,最后停留在右边第一个大于target的点。
值得注意的是如果最大的都小于target,要特殊处理。
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 {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int n=nums.size();
vector<int> ans;
if(n==0){
ans.push_back(-1);
ans.push_back(-1);
return ans;
}
int left1=0,right1=n,left2=0,right2=n;
int left,right;
int mid1,mid2;
while(left1<right1){
mid1=(left1+right1)/2;
if(target<=nums[mid1]){
right1=mid1;
}
else{
left1=mid1+1;
}
}
//cout<<left1<<endl;
//cout<<right1<<endl;
if(right1>=n||nums[right1]!=target){
left=-1;
}
else{
left=left1;
}
while(left2<right2){
mid2=(left2+right2)/2;
if(target>=nums[mid2]){
left2=mid2+1;
}
else{
right2=mid2;
}
}
//cout<<left2<<endl;
//cout<<right2<<endl;
if(right2-1>=n||nums[right2-1]!=target){
right=-1;
}
else{
right=right2-1;
}
ans.push_back(left);
ans.push_back(right);
return ans;
}
};
道理很简单,求左边界,相等就往左,最后停留在左边第一个target点。右边界,相等就往右,最后停留在右边第一个大于target的点。
值得注意的是如果最大的都小于target,要特殊处理。
相关文章推荐
- 小白笔记--------------------------leetcode 34. Search for a Range
- LeetCode 34 Search for a Range
- LeetCode 34.Search for a Range
- leetcode 34 -- Search for a Range
- [Leetcode 34, Medium] Search for a Range
- leetCode 34.Search for a Range (搜索范围) 解题思路和方法
- [Leetcode 89] 34 Search for a Range
- [LeetCode 34] Search for a Range
- Search for a Range - LeetCode 34
- leetcode_34——Search for a Range(二分查找)
- [leetcode 34] Search for a Range
- LeetCode_34---Search for a Range
- LeetCode 34 — Search for a Range(C++ Java Python)
- leetcode 34: Search for a Range
- [LeetCode] Search for a Range [34]
- [LeetCode]34 Search for a Range
- leetcode[34]Search for a Range
- 【LeetCode 34】Search for a Range
- [Leetcode] 34. Search for a Range
- LeetCode 34: Search for a Range