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

    本题和search for a range比较类似,代码如下:

     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         int low = 1;
     7         int high = n;
     8         while(low < high) {
     9             int mid = low + (high - low) / 2;
    10             if(isBadVersion(mid)) high = mid;
    11             else{
    12                 low = mid+1;
    13             }
    14         }
    15         return low;
    16     }
    17 }
    18 // the run time complexity could be O(logn), the space complexity could be O(1);
  • 相关阅读:
    致亲爱的304
    C语言中简单的for循环和浮点型变量
    C程序内存管理
    变量
    我哭了
    那一场邂逅
    如何修改安卓项目的图标
    Android requires compiler compliance level 5.0 or 6.0. Found '1.4' instead.解决方法
    Android 异步加载
    大家好,第一次用博客记录一些东西
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6477975.html
Copyright © 2011-2022 走看看