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.

二. 题目分析

题目说了一堆,一開始并不知道是想让干什么。

后来去网上查了题意,引用例如以下:

你是一名产品经理,并领导团队开发一个新产品。不幸的是,产品的终于版本号没有通过质量检測。因为每个版本号都是基于上一个版本号开发的,因此某一个损坏的版本号之后的全部版本号全都是坏的。

如果有n个版本号[1, 2, …, n],如今你须要找出第一个损坏的版本号,它导致全部后面的版本号都坏掉了。

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

原来仅仅需实现相似于Search for a Range 的功能,推断坏版本号的函数bool isBadVersion(version)题目已经提供,无需纠结怎样操作,这里还是使用二分查找来解决这个问题。

三. 演示样例代码

期初使用例如以下代码一直提示:Time Limit Exceeded

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low = 1, high = n;
        int midIndex = 0;
        while (low <= high)
        {
            midIndex = (low + high) / 2;
            if (isBadVersion(midIndex))
                high = midIndex - 1;
            else
                low = midIndex + 1;
        }
        return low;
    }
};

检查了一段时间,发现当n取非常大的数时出现故障,原来是语句midIndex = (low + high) / 2; 直接相加时溢出。导致循环超时,该用下面代码Accept。

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int low = 1, high = n;
        int midIndex = 0;
        while (low <= high)
        {
            midIndex = low + (high - low) / 2;
            if (isBadVersion(midIndex))
                high = midIndex - 1;
            else
                low = midIndex + 1;
        }
        return low;
    }
};

四. 小结

该题的难度在Search for a Range 之下。但出现了数据溢出的问题,因此对于简单一些的题也时刻不能掉以轻心啊。

【推广】 免费学中医,健康全家人
原文地址:https://www.cnblogs.com/zhchoutai/p/8846000.html