-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFirstBadVersion.java
More file actions
39 lines (35 loc) · 1.06 KB
/
FirstBadVersion.java
File metadata and controls
39 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class FirstBadVersion extends VersionControl {
//Binary search. O(logn) time and O(1) space
public int firstBadVersion(int n) {
int low = 1;
//Cannot be n+1 since it would overflow if n is max_integer.
int high = n;
while (low < high) {
int mid = low + (high - low) / 2;
if (isBadVersion(mid)) {
high = mid;
} else {
low = mid + 1;
}
}
return isBadVersion(low) ? low : 0;
}
//Another algorithm. Minimum calls to isBadVersion
public int firstBadVersion(int n) {
int id = 0;
int low = 1;
int high = n;
while (low <= high) {
int mid = low + (high - low) / 2;
if (isBadVersion(mid)) {
id = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return id;
}
}