题目大意:给你一个API查询版本是否坏了,让你找出第一个坏掉的版本。
Problem:
https://leetcode.com/problems/first-bad-version/description/
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.
Solution 1: Brute Force
Time Complexity: O(n) TLE
Space Complexity: O(1)
Solution 2: Binary Search
Time Complexity: O(logn)
Space Complexity: O(1)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Forward declaration of isBadVersion API. bool isBadVersion(int version); // Author: Huahua // Running time: 2 ms class Solution { public: int firstBadVersion(int n) { int l = 1; int r = n; while (l < r) { int m = l + (r - l) / 2; if (isBadVersion(m)) r = m; else l = m + 1; } return l; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment