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 }
  • 相关阅读:
    BZOJ 3514 Codechef MARCH14 GERALD07加强版
    WT
    Codeforces 348
    POI 2010
    Codeforces 336
    MVC实例及用三层架构实现对学生信息的增删改查
    欠拟合和过拟合
    线性回归案例
    梯度下降法介绍
    线性回归的损失函数和梯度下降
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5077398.html
Copyright © 2011-2022 走看看