zoukankan      html  css  js  c++  java
  • LeetCode——First Bad Version

    Description:

    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.

    二分法

    /* The isBadVersion API is defined in the parent class VersionControl.
          boolean isBadVersion(int version); */
          
    
    public class Solution extends VersionControl {
        public int firstBadVersion(int n) {
            
            //0 0 0 0 0 1 1 1 1 1
            int start=1, end=n;
            int mid;
            while(start + 1< end) {
                mid=start + (end - start)/2;
                //写成mid = (start+end) / 2,会造成整数越界,变成死循环。
                //写成上边这样就能防止越界问题。
                if(isBadVersion(mid)) {
                    end = mid;
                }
                else {
                    start = mid;
                }
            }
            if(isBadVersion(start)) {
                return start;
            }
            else {
                return end;
            }
            
        }
    }
  • 相关阅读:
    2012航拍香港
    2012航拍香港
    论玩镜头的三种境界[转自无忌fruitbear]
    论玩镜头的三种境界[转自无忌fruitbear]
    认识镜头的MTF值
    认识镜头的MTF值
    宾得十大名镜
    宾得十大名镜
    两个输入通道怎么判断通道顺序
    增加新功能和未知的修改操作
  • 原文地址:https://www.cnblogs.com/wxisme/p/4841438.html
Copyright © 2011-2022 走看看