Lintcode: First Bad Version 解题报告

时间:2023-09-06 13:40:20

First Bad Version

http://lintcode.com/en/problem/first-bad-version

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

You can determine whether a version is bad by the following interface:

Java:
    public VersionControl {
        boolean isBadVersion(int version);
    }
C++:
    class VersionControl {
    public:
        bool isBadVersion(int version);
    };
Python:
    class VersionControl:
        def isBadVersion(version)

Find the first bad version.

Note

You should call isBadVersion as few as possible.

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

Example

Given n=5

Call isBadVersion(3), get false

Call isBadVersion(5), get true

Call isBadVersion(4), get true

return 4 is the first bad version

Challenge

Do not call isBadVersion exceed O(logn) times.

Tags Expand

Lintcode:  First Bad Version 解题报告

SOLUTION 1:

九章算法模板解法,注意,一定要使用left + 1 < right 作为while的条件,这样子不会产生死循环和越界的情况。
 /**
* public class VersionControl {
* public static boolean isBadVersion(int k);
* }
* you can use VersionControl.isBadVersion(k) to judge wether
* the kth code version is bad or not.
*/
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
// write your code here
if (n == 1) {
return 1;
} int left = 1;
int right = n; while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (VersionControl.isBadVersion(mid)) {
right = mid;
} else {
left = mid;
}
} if (VersionControl.isBadVersion(left)) {
return left;
} return right;
}
}

SOLUTION 2:

也可以简化一点儿:

 /**
* public class VersionControl {
* public static boolean isBadVersion(int k);
* }
* you can use VersionControl.isBadVersion(k) to judge wether
* the kth code version is bad or not.
*/
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
// write your code here
if (n == 1) {
return 1;
} int left = 1;
int right = n; while (left < right) {
int mid = left + (right - left) / 2;
if (VersionControl.isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
} return right;
}
}