Easy 278. 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 APl 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 <= bad <= n <= 2^31 - 1
isBadVersion
API 呼叫次數越少越好
Binary Search
API
解題思路
這題的核心概念是使用二分搜尋來最小化 API 呼叫次數:
程式碼實作
程式碼說明
- 二分搜尋的重點:
在尋找中間點時,我們需要特別注意計算方式:
複雜度分析
- 時間複雜度: O(log n)
- 使用二分搜尋,每次將搜尋範圍減半
- n 是版本總數
- 空間複雜度: O(log n)
- 使用遞迴,堆疊深度為 log n
- 如果使用迴圈則為 O(1)
解題心得
- 二分搜尋的應用
- 當資料有序且需要找到特定條件的第一個元素時
- 可以大幅減少搜尋次數
- 程式碼優化
- 使用遞迴可以讓程式碼更簡潔易讀
- 但要注意堆疊溢出的風險
- 實務應用
::