From deabec3eae0a0988263525412313e08c90623a55 Mon Sep 17 00:00:00 2001 From: juan Date: Sat, 9 Jul 2022 10:15:12 +0800 Subject: [PATCH] vault backup: 2022-07-09 10:15:12 --- OJ notes/pages/Leetcode First-Bad-Version.md | 35 ++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/OJ notes/pages/Leetcode First-Bad-Version.md b/OJ notes/pages/Leetcode First-Bad-Version.md index f96ea3e..3aff7e6 100644 --- a/OJ notes/pages/Leetcode First-Bad-Version.md +++ b/OJ notes/pages/Leetcode First-Bad-Version.md @@ -61,10 +61,45 @@ Note that [[Leetcode First-Bad-Version#Constraints]], n can be 2**31, which mean To address that, according to [[Binary Search Algorithm#How to implement Binary search]], use `mid = l + (r - l) / 2` +In my first iteration, I use a `first` variable to keep track of the first bad version. +Later I realized that by the definition of Bi-search, left boundary will converge to the first one. + ### Solution +Second version, 0ms +```cpp +// The API isBadVersion is defined for you. +// bool isBadVersion(int version); + +class Solution { +public: + int firstBadVersion(int n) { + // variant of BS + // 1-indexed + + int r = n; + int l = 1; + int mid; + + do { + mid = l + (r - l) / 2; + + if (isBadVersion(mid)) { + // Search left + r = mid - 1; + } else { + l = mid + 1; + } + } while (l <= r); + + return l; + } +}; +``` + +First iteration, 4ms ```cpp // The API isBadVersion is defined for you. // bool isBadVersion(int version);