您的位置:首页 > 其它

[leetcode]二分查找总结

2014-08-02 13:37 387 查看

Search for a Range

1.最简单的想法,用最普通的二分查找,找到target,然后向左右扩张,大量的重复的target,就会出现O(n)效率。

class Solution {
public int[] searchRange(int[] A, int target) {
int ans[]=new int[2];
int a= bserch(A,target);
if(a==-1) {ans[0]=-1;ans[1]=-1; return ans;}
//left
int b=a-1;
while(b>=0&&A[b]==target) b--;
ans[0]=b+1;
b=a+1;

while(b<=A.length-1&&A[b]==target) b++;
ans[1]=b-1;
return ans;

}

public  int bserch(int A[],int target)
{
int low=0;
int end=A.length-1;
while(low<=end)
{
int mid=(low+end)>>1;
if(A[mid]==target) return mid;
else if(A[mid]<target)  low=mid+1;
else   end=mid-1;

}

return -1;
}

}


2.二分查找加入第一个大的位置(上届),第一个大于等于它的位置(下界)

class Solution {
public int[] searchRange(int[] A, int target) {
int ans[]=new int[2];
int a= bserch(A,target);
if(a==-1) {ans[0]=-1;ans[1]=-1; return ans;}
//left
int b=a-1;
while(b>=0&&A[b]==target) b--;
ans[0]=b+1;
b=a+1;

while(b<=A.length-1&&A[b]==target) b++;
ans[1]=b-1;
return ans;

}
//其实难点就是A[mid]==target,如何调整low和high
public  int bserch(int A[],int target)
{
int low=0;
int end=A.length-1;
while(low<=end)
{
int mid=(low+end)>>1;
if(A[mid]==target) return mid;
else if(A[mid]<target)  low=mid+1;
else   end=mid-1;

}

return -1;
}
//第一个大于target的
public int  upperbound(int A[],int target) // the first one larger than target
{
int low=0;
int end=A.length-1;
while(low<=end)
{
int mid=(low+end)>>1;
if(A[mid]>target) end=mid-1;
else low=mid+1;

}
return low;
}
public int  lowbound(int A[],int target) // the first one larger or equal  target
{
int low=0;
int end=A.length-1;
while(low<=end)
{
int mid=(low+end)>>1;
if(A[mid]>=target) end=mid-1;
else low=mid+1;

}
return low;
}

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