2017.9.26
对二分查找的认知达到的新的高度,简直不明白为什么还会有这种操作。
求取中间数的时候,如果我用 mid = (low + height)/2 就会超时;但是我如果用 mid = low + (height - low)/2 就会AC。真的是很鸡贼啊。
后来问了问师兄明白了,前一种方法是可能会超过int上限的,用第二种方法更为保险一些。
受教了受教了。
/**
* public class SVNRepo {
* public static boolean isBadVersion(int k);
* }
* you can use SVNRepo.isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
// write your code here
if( n <= 0){
return n;
}
int low = 1;
int height = n;
int mid = 0;
while(low < height)
{
mid = low + (-low + height)/2;
if(SVNRepo.isBadVersion(mid))
height = mid-1;
else
low = mid+1;
}
return low;
}
}