您的位置:首页 > 其它

LeetCode First Bad Version

2015-09-26 02:06 274 查看
原题链接在这里:https://leetcode.com/problems/first-bad-version/

尽可能少的使用API, 就想到Binary Search. 查中点是不是,若是bad version, 就在左边继续查,若不是bad version, 就在右边继续查找。

Note:  求中点mid时,要用 mid = left +(right - left)/2, 不能使用 mid = (left + right)/2 因为loop 过程中(left + right)可能超过 Integer.MAX_VALUE, overflow了。

AC Java:

/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */

public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1;
int right = n;
int res = 0;
while(left<=right){
int mid = left + (right - left)/2;
if(isBadVersion(mid)){
right = mid-1;
}else{
left = mid+1;
}
}
return left;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: