First Bad Version

Question

Problem Statement

The code base version is an integer start from 1 to n. One day, someone
committed a bad version in the code case, so it caused this version and the
following versions are all failed in the unit tests. Find the first bad
version.

You can call isBadVersion to help you determine which version is the first
bad one. The details interface can be found in the code’s annotation part.

Example

Given n = 5:

  1. isBadVersion(3) -> false
  2. isBadVersion(5) -> true
  3. isBadVersion(4) -> true

Here we are 100% sure that the 4th version is the first bad version.

Note

Please read the annotation in code area to get the correct way to call
isBadVersion in different language. For example, Java is
VersionControl.isBadVersion(v)

Challenge

You should call isBadVersion as few as possible.

题解

基础算法中 Binary Search 的 lower bound. 找出满足条件的下界即可。

Python

  1. #class VersionControl:
  2. # @classmethod
  3. # def isBadVersion(cls, id)
  4. # # Run unit tests to check whether verison `id` is a bad version
  5. # # return true if unit tests passed else false.
  6. # You can use VersionControl.isBadVersion(10) to check whether version 10 is a
  7. # bad version.
  8. class Solution:
  9. """
  10. @param n: An integers.
  11. @return: An integer which is the first bad version.
  12. """
  13. def findFirstBadVersion(self, n):
  14. lb, ub = 0, n + 1
  15. while lb + 1 < ub:
  16. mid = lb + (ub - lb) / 2
  17. if VersionControl.isBadVersion(mid):
  18. ub = mid
  19. else:
  20. lb = mid
  21. return lb + 1

C++

  1. /**
  2. * class VersionControl {
  3. * public:
  4. * static bool isBadVersion(int k);
  5. * }
  6. * you can use VersionControl::isBadVersion(k) to judge whether
  7. * the kth code version is bad or not.
  8. */
  9. class Solution {
  10. public:
  11. /**
  12. * @param n: An integers.
  13. * @return: An integer which is the first bad version.
  14. */
  15. int findFirstBadVersion(int n) {
  16. int lb = 0, ub = n + 1;
  17. while (lb + 1 < ub) {
  18. int mid = lb + (ub - lb) / 2;
  19. if (VersionControl::isBadVersion(mid)) {
  20. ub = mid;
  21. } else {
  22. lb = mid;
  23. }
  24. }
  25. return lb + 1;
  26. }
  27. };

Java

  1. /**
  2. * public class VersionControl {
  3. * public static boolean isBadVersion(int k);
  4. * }
  5. * you can use VersionControl.isBadVersion(k) to judge whether
  6. * the kth code version is bad or not.
  7. */
  8. class Solution {
  9. /**
  10. * @param n: An integers.
  11. * @return: An integer which is the first bad version.
  12. */
  13. public int findFirstBadVersion(int n) {
  14. int lb = 0, ub = n + 1;
  15. while (lb + 1 < ub) {
  16. int mid = lb + (ub - lb) / 2;
  17. if (VersionControl.isBadVersion(mid)) {
  18. ub = mid;
  19. } else {
  20. lb = mid;
  21. }
  22. }
  23. return lb + 1;
  24. }
  25. }

源码分析

lower bound 的实现,这里稍微注意下lb 初始化为 0,因为 n 从1开始。ub 和 lb 分别都在什么条件下更新就好了。另外这里并未考虑 n <= 0 的情况。

复杂度分析

二分搜索,O(\log n).