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

    题目大意:

    你是一名产品经理,正在领导团队开发一个新产品。不幸的是,产品的最新版本没有通过质量检测。由于每一个版本都是基于上一个版本开发的,某一个损坏的版本之后的所有版本全都是坏的。

    假设有n个版本[1, 2, ..., n],你想要找出第一个损坏的版本,它导致所有后面的版本都坏掉了。

    给你一个API bool isBadVersion(version),返回某一个版本是否损坏。实现一个函数找出第一个损坏的版本。你应该最小化调用API的次数。

    解题思路:

    二分法(Binary Search),详见代码。

     1 public class Solution extends VersionControl {
     2     public int firstBadVersion(int n) {
     3         int start = 1, end = n;
     4         while (start + 1 < end) {
     5             int mid = (end - start) / 2 + start; //如果用(end+start)/2会超时!
     6             if (isBadVersion(mid)) {
     7                 end = mid;
     8             } else {
     9                 start = mid;
    10             }
    11         }
    12         if (isBadVersion(start)) {
    13             return start;
    14         }
    15         return end;
    16 
    17     }
    18 }

    r

  • 相关阅读:
    [转]GPS原始数据说明
    [转]标准USB,MiniUSB接口定义
    warning C4819: 该文件包含不能在当前代码页(936)中表示的字符
    with用法
    turn out用法
    keep用法
    Stop doing和Stop to do和Stop...from doing有什么不同
    figure用法
    wanna用法
    seem用法
  • 原文地址:https://www.cnblogs.com/hygeia/p/4834898.html
Copyright © 2011-2022 走看看