You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
Suppose you have n
versions [1,
2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
You are given an API bool isBadVersion(version)
which will return whether version
is
bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
二分查找,查找的时候进入子区间前先检查一下避免错过查找位置。
因为这里查找的是第一个”坏的“位置,这个位置靠近左边,应该在进入左子区间前进行检查。
public int firstBadVersion(int n)
{
return find(1, n);
}
public int find(int lo,int hi)
{
if(lo==hi)
return lo;
int mid=(int) (((long)lo+(long)hi)>>1);
if(isBadVersion(mid))
{
if(mid-1>=lo&&isBadVersion(mid-1))
return find(lo, mid-1);
return mid;
}
return find(mid+1, hi);
}
或者,换一种思路,从左边尽量地延伸。
https://discuss.leetcode.com/topic/26272/o-lgn-simple-java-solution/2
public int firstBadVersion(int n) {
int start = 1, end = n;
while (start < end) {
int mid = start + (end-start) / 2;
if (!isBadVersion(mid)) start = mid + 1;
else end = mid;
}
return start;
}
---------------------------------------------------------------------------------------------
二分查找,若该元素出现多次,返回第一次出现的位置
public static int getPos(int[] A, int n, int val) {
int lo=0,hi=n-1;
int mid=lo;
while(lo<hi){
mid=lo+(hi-lo)/2;
if(A[mid]<val){
lo=mid+1;
}else{
hi=mid;
}
}
return A[lo]==val?lo:-1;
}
二分查找,若该元素出现多次,返回最后一次出现的位置
public static int getPos(int[] A, int n, int val) {
int lo=0,hi=n-1;
int mid=lo;
while(lo<hi){
mid=lo+(hi-lo+1)/2;
if(A[mid]>val){
hi=mid-1;
}else{
lo=mid;
}
}
return A[hi]==val?hi:-1;
}