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 }
  • 相关阅读:
    构建之法阅读笔记03
    12.16第三周总结
    构建之法阅读笔记02
    12.9第二周周总结
    四则运算2
    构建之法阅读笔记01
    12.2第一周总结
    课堂练习-增加信息
    软件工程00
    web自动化测试---web页面元素的定位
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5077398.html
Copyright © 2011-2022 走看看