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

  • 相关阅读:
    查看Sql Server2016 是否激活
    MSSQL 账户访问视图权限的设置
    Vue 前端验证码
    (攻防世界) -- pwn入门 -- 新手区1 -- CGfsb
    .NET Core自动注册服务
    C# Graphics 生成文字圆形头像
    Codeforces Round #729 (Div. 2) C. Strange Function
    Codeforces Round #710 (Div. 3) ABCDE 题解
    Codeforces Round #708 (Div. 2) ABC1C2题解
    Codeforces Round #706 (Div. 2) D. Let's Go Hiking 博弈 思维
  • 原文地址:https://www.cnblogs.com/hygeia/p/4834898.html
Copyright © 2011-2022 走看看