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 {
public:
vector<int> searchRange(int A[], int n, int target) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(NULL==A || n<1)
return vector<int> (2,-1);
int ibeg=0,iend=n-1;
vector<int> result;
int left=0,right=0;
while(ibeg <= iend)
{
int imid=ibeg+(iend-ibeg)/2;
if(A[imid]==target)
{
//left
left=find(A,ibeg,imid,target,true);
//right
right=find(A,imid,iend,target,false);
result.push_back(left);result.push_back(right);
return result;
}
else if(A[imid]<target)
{
ibeg = imid+1;
}
else
{
iend = imid-1;
}
}
return vector<int> (2,-1);
}
int find(int A[],int ibeg,int iend,int target,bool bleft)
{
int pos = -1;
if(bleft)//left
{
pos = iend;
iend--;
while(ibeg<=iend)
{
int imid = ibeg+(iend-ibeg)/2;
if(A[imid]==target)
{
pos = imid;
iend = imid-1;
}
else
ibeg = imid+1;
}
return pos;
}
else
{
pos = ibeg;
++ibeg;
while(ibeg<=iend)
{
int imid = ibeg+(iend-ibeg)/2;
if(A[imid]==target)
{
pos = imid;
ibeg = imid+1;
}
else
iend = imid-1;
}
return pos;
}
}
};
写的有点臃肿,贴个简洁的:
public class Solution {
public int[] searchRange(int[] A, int target) {
// Start typing your Java solution below
// DO NOT write main() function
int[] res = new int[2];
res[0] = lowerbound(A,target);
res[1] = upperbound(A,target);
return res;
}
public static int upperbound(int[] num, int target){
//find last 2,
int low=0;
int high=num.length - 1;
int mid = low + (high-low+1)/2;
while(low<high){
mid = low + (high-low+1)/2;
if(num[mid]<=target){
low = mid;
} else {
high = mid - 1;
}
}
return num[low] == target ? low : -1;
}
public static int lowerbound(int[] num, int target){
//find first 2.
int low=0;
int high=num.length - 1;
int mid = low + (high-low)/2;
while(low<high) {
mid = low + (high-low)/2;
if(num[mid]>=target){
high = mid;
} else {
low = mid + 1;
}
}
return num[high] == target ? high : -1;
}
}
lower主要就是
if(num[mid]>=target){
high = mid;
} else {
low = mid + 1;
}
递归的:
http://www.cnblogs.com/remlostime/archive/2012/11/14/2770148.html