【LeetCode】- First Bad Version

1、题目描述

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.

  • Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version.

2、问题描述:

  • 如果一个商品是坏的,那么他后面的都是坏的,找到第一个坏的地方。

3、问题关键:

  • 典型的二分法使用,前面一半是好的,后面一半是坏的。

4、C++代码:

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

class Solution {
public:
    int firstBadVersion(int n) {
        int l = 1, r = n;
        while(l < r) {
            int mid = l + (r - l)/2;//防止里面的大数据超过范围。
            if (isBadVersion(mid)) r = mid;//r = mid,那么l = mid + 1;
            else l = mid + 1;
        }
        return r;//找到坏的地方。
    }
};
    原文作者:邓泽军_3679
    原文地址: https://www.jianshu.com/p/4905d53865e3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞