返回

[Leetcode]278. First Bad Version(C++)

题目描述

题目链接:278. 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 returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

例子

例子 1

Input: n = 5, bad = 4 Output: 4 Explanation: call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.

例子 2

Input: n = 1, bad = 1 Output: 1

Constraints

  • 1 <= bad <= n <= 2^31 - 1

解题思路

典型的二分查找题目,以 1 为左边界,n 为右边界开始用二分查找收缩范围即可,由于要找的是第一个 Bad Version,因此在搜索右边界时应该使 right = mid,而收缩左边界使应该是 left = mid + 1 (因为我们不需要 Good Version),最终结果是 leftright 会在第一个 Bad Version 处相遇,代码如下:

// The API isBadVersion is defined for you.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left = 1;
        int right = n;
        while (left < right) {
            int mid = ((long)left + right) / 2;
            if (isBadVersion(mid)) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }

        return left;
    }
};
  • 时间复杂度: O(logn)
  • 空间复杂度: O(1)

GitHub 代码同步地址: 278.FirstBadVersion.cpp

其他题目: GitHub: Leetcode-C++-Solution 博客: Leetcode-Solutions

Built with Hugo
Theme Stack designed by Jimmy