zoukankan      html  css  js  c++  java
  • leetcode 278. First Bad Version

    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.


    Example

    Given n = 5:

    isBadVersion(3) -> false
    isBadVersion(5) -> true
    isBadVersion(4) -> true
    

    Here we are 100% sure that the 4th version is the first bad version.

    分析:

    代码库的版本号是从 1 到 n 的整数。某一天,有人提交了错误版本的代码,因此造成自身及之后版本的代码在单元测试中均出错。请找出第一个错误的版本号。

    你可以通过 isBadVersion 的接口来判断版本号 version 是否在单元测试中出错。

    给出 n=5

    调用isBadVersion(3),得到false

    调用isBadVersion(5),得到true

    调用isBadVersion(4),得到true

    此时我们可以断定4是第一个错误的版本号

    /**
     * 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) {
            int start = 0, end  = n;
            while (start + 1 < end) {
                int mid = start + (end - start) / 2;
                if (SVNRepo.isBadVersion(mid)) {
                    end = mid;
                } else {
                    start = mid;
                }
            }
                
            if (SVNRepo.isBadVersion(start)) {
                return start;
            }
            return end;
        }
    }
  • 相关阅读:
    代理模式
    spring aop
    mybatis从入门到精通(其他章节)
    mybatis从入门到精通(第6章)
    Java中Compareable和Comparator两种比较器的区别
    Java的equals方法的使用技巧
    Dubbo的配置过程,实现原理及架构详解
    什么是IPFS?IPFS与区块链有什么关系
    leetCode242 有效的字母异位词
    需要多个参数输入时-----------------考虑使用变种的Builder模式
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5755043.html
Copyright © 2011-2022 走看看