Skip to content

Commit dd4b6f6

Browse files
authoredSep 5, 2024
Create First Bad Version
1 parent 9cb0b39 commit dd4b6f6

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
 
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
想法:維護第一個bad version出現的位置,所以 l , r 之間要取 floor((l + r) / 2 ) 即可
2+
注意:因為l , r 很大,所以如果之間寫成 (l + r) / 2 會在 l + r 時overflow ,可改成 l + (r - l) / 2
3+
4+
Time Complexity : O(logn) for binary search
5+
Space Complexity : O(1) for variables
6+
7+
// The API isBadVersion is defined for you.
8+
// bool isBadVersion(int version);
9+
10+
class Solution {
11+
public:
12+
int firstBadVersion(int n) {
13+
int l = 1 , r = n ;
14+
while ( l < r ) {
15+
int m = l + (r - l) / 2 ;
16+
if ( isBadVersion(m) )
17+
r = m ;
18+
else
19+
l = m + 1 ;
20+
}
21+
22+
return r ;
23+
}
24+
};

0 commit comments

Comments
 (0)