zoukankan      html  css  js  c++  java
  • Leetcode: 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.

     m = (l + r) /2 get TLE because l+r can lead to an overflow

    an alternative way to do it is: m = l + (r-l)/2

     1 /* The isBadVersion API is defined in the parent class VersionControl.
     2       boolean isBadVersion(int version); */
     3 
     4 public class Solution extends VersionControl {
     5     public int firstBadVersion(int n) {
     6         if (n <= 1) return 1;
     7         int l=1, r=n;
     8         while(l <= r) {
     9             int m = l + (r-l)/2;
    10             if (isBadVersion(m)) {
    11                 r = m-1;
    12             }
    13             else {
    14                 l = m+1;
    15             }
    16         }
    17         return l;
    18     }
    19 }
  • 相关阅读:
    k8s中文网
    python range用法
    python 日志滚动 分文件
    python 语法
    flask 中文编码解码
    python的杨辉三角
    mysql8.0.4以后修改密码方式变更
    flask学习视频
    oralce的lag和lead函数
    JNI 各类数据类型处理
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5077398.html
Copyright © 2011-2022 走看看