您的位置:首页 > 其它

[leetcode] Search for a Range

2014-04-15 21:36 295 查看
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]
.

找到左边第一个target 以及右边第一个target;

class Solution {
public:
int findLeftMost(int A[], int n, int target)
{
if(n == 0) return -1;
int left = 0;
int right = n-1;
while(left < right)
{
int mid = left+(right-left)/2;
if(A[mid] >= target) right = mid;
else left = mid+1;
}
if(A[left] == target) return left;
else return -1;
}
int findRightMost(int A[], int n, int target)
{
if(n == 0) return -1;
int left = 0;
int right = n-1;
while(left <= right)
{
int mid = left+(right-left)/2;
if(A[mid] > target) right = mid-1;
else left = mid+1;
}
if(A[right] == target) return right;
else return -1;
}
vector<int> searchRange(int A[], int n, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int startPos = findLeftMost(A, n, target);
int endPos = findRightMost(A, n, target);
vector<int> ans(2);
ans[0] = startPos; ans[1] = endPos;
return ans;

/*int findLeftMost(int A[], int n, int target)
{
if(n==0) return -1;
int l=0;
int r=n-1;
while( l < r)
{
int mid=(l+r)/2;
if(A[mid] <= target) r=mid;
else
l=mid+1;
}
if(A[l]==target) return l;
else
return -1;

}
int findRightMost(int A[], int n, int target)
{
if(n==0) return -1;
int l=0;
int r=n-1;
while( l < r)
{
int mid=(l+r)/2;
if(A[mid] > target) l=mid +1;
else
r=mid;
}
if(A[r]==target) return r;
else
return -1;

}

vector<int> searchRange(int A[], int n, int target) {
vector<int> res(2);
res.clear();
int start=findLeftMost( A,  n,  target);
int end=findRightMost( A,  n,  target);
res[0]=start;
res[1]=end;*/

/* if(n==0 || n==1 && A[0]!=target)
{
res.push_back(-1);
res.push_back(-1);
}
if(n==1 && A[0]==target)
{
res.push_back(0);
res.push_back(0);
}
for(int i=1,j=n ;i<j ;i++,j--)
{
if(A[i-1]==target )
res.push_back(i-1);
if(A[j-1]==target)
res.push_back(j-1);
}
vector<int>::iterator it;
it=res.begin();
if(res.size()==1)
{
res.push_back(*it);
}
if(res.empty())
{
res.push_back(-1);
res.push_back(-1);
}*/
/* int low=1,high=n;
while(low<high)
{
int mid=( low + high )/2;
while(target>A[mid-1] && target==A[mid]||target==A[mid] && target < A[mid+1] )
{
res.push_back(mid);
}

if(target < A[mid]) high=mid-1;
else
low=mid+1;
}*/
/*return res;*/

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