1. 程式人生 > 其它 >【LeetCode】278. First Bad Version 第一個錯誤的版本(Easy)(JAVA)

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

技術標籤:Leetcodejavaleetcode面試演算法資料結構

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

題目地址: https://leetcode.com/problems/first-bad-version/

題目描述:

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.

Example 1:

Input: n = 5, bad = 4
Output: 4
Explanation:
call isBadVersion(3) -> false
call isBadVersion(5)-> true
call isBadVersion(4)-> true
Then 4 is the first bad version.

Example 2:

Input: n = 1, bad = 1
Output: 1

Constraints:

  • 1 <= bad <= n <= 2^31 - 1

題目大意

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

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

你可以通過呼叫bool isBadVersion(version)介面來判斷版本號 version 是否在單元測試中出錯。實現一個函式來查詢第一個錯誤的版本。你應該儘量減少對呼叫 API 的次數。

解題方法

  1. 採用二分法,時間複雜度 O(logn)
  2. 主要就是看如果 isBadVersion(mid), 要往那邊走;因為要判斷第一個壞的地方,所以這時候還需要往前走也就是 end = mid - 1
public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int start = 1;
        int end = n;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (isBadVersion(mid)) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return start;
    }
}

執行耗時:18 ms,擊敗了29.17% 的Java使用者
記憶體消耗:35.3 MB,擊敗了59.53% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新