1. 程式人生 > >LeetCode 278. 第一個錯誤的版本(First Bad Version)

LeetCode 278. 第一個錯誤的版本(First Bad Version)

new pil lse pro lean href start strong 版本號

278. 第一個錯誤的版本

LeetCode278. First Bad Version

題目描述
你是產品經理,目前正在帶領一個團隊開發新的產品。不幸的是,你的產品的最新版本沒有通過質量檢測。由於每個版本都是基於之前的版本開發的,所以錯誤的版本之後的所有版本都是錯的。

假設你有 n 個版本 [1, 2, ..., n],你想找出導致之後所有版本出錯的第一個錯誤的版本。

你可以通過調用 bool isBadVersion(version) 接口來判斷版本號 version 是否在單元測試中出錯。實現一個函數來查找第一個錯誤的版本。你應該盡量減少對調用 API 的次數。

示例:
給定 n = 5,並且 version = 4 是第一個錯誤的版本。

調用 isBadVersion(3) -> false
調用 isBadVersion(5) -> true
調用 isBadVersion(4) -> true

所以,4 是第一個錯誤的版本。

Java 實現

/* 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 i = 1, j = n, m;
        while (i < j) {
            m = i + (j - i) / 2;
            if (!isBadVersion(m)) {
                i = m + 1;
            } else {
                j = m;
            }
        }
        return j;
    }
}
public class Solution {
    public int firstBadVersion(int n, int version) {
        int start = 1, end = n;
        while (start < end) {
            int mid = start + (end - start) / 2;
            if (!isBadVersion(mid, version)) start = mid + 1;
            else end = mid;
        }
        return start;
    }

    public boolean isBadVersion(int v, int version) {
        if (v >= version) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.firstBadVersion(5, 4));
    }
}

參考資料

  • https://leetcode.com/problems/first-bad-version/
  • https://leetcode-cn.com/problems/first-bad-version/

LeetCode 278. 第一個錯誤的版本(First Bad Version)