LeetCode Note Java 00278:First Bad Version

情境題:找出第一個壞版本。

題目

First Bad Version Easy

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.

解法

假設好版本是 false,壞版本是 true,那各版本就可以如此呈現:[f, f, f, f, t, t, t, t]

要找的是第一個 true。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */

public class Solution extends VersionControl {
public int firstBadVersion(int n) {
int left = 1, right = n;
while (left < right) {
int middle = left + (right - left) / 2; // 重點:避免相加數字過大導致溢出。
if (isBadVersion(middle)) {
right = middle;
} else {
left = middle + 1; // 一定是這步導致離開迴圈。
}
}
return left; // 離開迴圈時 left 會是第一個 t。
}
}

檢討

這題乍看之下就是二元搜尋法,以為很簡單,但是很多條件不好想像,要一次正確或是執行時間達標都不容易。

要注意離開迴圈時的條件才能知道誰是答案。

參考資料

An clear way to use binary search