zoukankan      html  css  js  c++  java
  • LintCode-First Bad Version

    The code base version is an integer and start from 1 to n. One day, someone commit a bad version in the code case, so it caused itself and the following versions are all failed in the unit tests.

    You can determine whether a version is bad by the following interface: 

     

    Java:
        public VersionControl {
            boolean isBadVersion(int version);
        }
    C++:
        class VersionControl {
        public:
            bool isBadVersion(int version);
        };
    Python:
        class VersionControl:
            def isBadVersion(version)

     

    Find the first bad version.

    Note

    You should call isBadVersion as few as possible. 

    Please read the annotation in code area to get the correct way to call isBadVersion in different language. For example, Java is VersionControl.isBadVersion.

    Example

    Given n=5

    Call isBadVersion(3), get false

    Call isBadVersion(5), get true

    Call isBadVersion(4), get true

    return 4 is the first bad version

    Challenge

    Do not call isBadVersion exceed O(logn) times.

    Solution:

     1 /**
     2  * public class VersionControl {
     3  *     public static boolean isBadVersion(int k);
     4  * }
     5  * you can use VersionControl.isBadVersion(k) to judge wether
     6  * the kth code version is bad or not.
     7 */
     8 class Solution {
     9     /**
    10      * @param n: An integers.
    11      * @return: An integer which is the first bad version.
    12      */
    13     public int findFirstBadVersion(int n) {
    14         if (n==1) return 1;
    15 
    16         int start = 1;
    17         int end = n;
    18         while (start<=end){
    19             int mid = start + (end-start)/2;
    20 
    21             if (!VersionControl.isBadVersion(mid))
    22                 start = mid +1;
    23             else {
    24                 if (mid==1 || !VersionControl.isBadVersion(mid-1))
    25                     return mid;
    26                 else end = mid-1;
    27             }
    28         }
    29 
    30         return -1;
    31     }
    32 }
  • 相关阅读:
    excel数据导入mySql数据库
    springboot-devtools实现项目的自动重启
    Java中List, Integer[], int[]的相互转换
    Postman代码测试工具如何用?
    git提交代码时,Unstaged changes如何过滤.class .log等文件
    Json字符串转map集合
    实现hibernate 的validator校验
    [转载]OpenSSL中文手册之命令行详解(未完待续)
    Openssl ASN.1 说明一 分享
    [转载]Parsing X.509 Certificates with OpenSSL and C
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4194930.html
Copyright © 2011-2022 走看看