• 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

  • 相关阅读:
    数据库30条规范
    数据库索引原理
    HashMap的实现原理
    Google 和 Baidu 常用的搜索技巧
    Arrays工具类十大常用方法
    fastjson将json格式null转化空串
    SolrCloud的介绍
    网页背景图片自适应浏览器大小
    addlinkedserver
    常用
  • 原文地址:https://www.cnblogs.com/hygeia/p/4834898.html
Copyright © 2020-2023  润新知