278. First Bad Version

原题链接:https://leetcode.com/problems/first-bad-version/description/``
实现如下:

/**
 * Created by clearbug on 2018/4/6.
 */
public class VersionControlSolution extends VersionControl {

    public int firstBadVersion(int n) {
        int start = 1;
        int end = n;
        while (start <= end) {
//            int medium = (start + end) / 2; // 不要使用这种方法,当 start 和 end 都接近 int 类型最大值时会导致溢出,以致 medium 可能成为负数
            int medium = start + (end - start) / 2;
            if (isBadVersion(medium)) {
                end = medium - 1;
            } else {
                start = medium + 1;
            }
        }
        return start;
    }
    
}
posted @ 2018-04-06 19:22  optor  阅读(109)  评论(0编辑  收藏  举报