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.

    就是一个找第一次出现的边沿的题目,方法是Binary Search, 只不过左右指针肯定会重合的,重合之后左指针所在的位置就是左边沿

    isBadVersion是个Class Method, 所以调用的方式是类的名字+方法名字

    * public class VersionControl {
    * public static boolean isBadVersion(int k);
    * }

     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         int l = 1;
    15         int r = n;
    16         while (l <= r) {
    17             int m = (l + r) / 2;
    18             if (VersionControl.isBadVersion(m)) {
    19                 r = m - 1;
    20             }
    21             else {
    22                 l = m + 1;
    23             }
    24         }
    25         return l;
    26     }
    27 }
  • 相关阅读:
    依赖注入
    ToDictionary() and ToList()
    Middleware详解
    仓储层的搭建
    Controller和View的交互
    Configuration配置信息管理
    开发工具
    60分钟Python快速学习(转)
    oracle PL/SQL(procedure language/SQL)程序设计之函数+过程+包(转)
    ssh无密码登陆(转)
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/4278295.html
Copyright © 2011-2022 走看看