vault backup: 2022-07-09 10:15:12
This commit is contained in:
parent
2d6259bb99
commit
deabec3eae
|
@ -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`
|
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.
|
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
|
### 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
|
```cpp
|
||||||
// The API isBadVersion is defined for you.
|
// The API isBadVersion is defined for you.
|
||||||
// bool isBadVersion(int version);
|
// bool isBadVersion(int version);
|
||||||
|
|
Loading…
Reference in a new issue