-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-278-First-Bad-Version.java
47 lines (39 loc) · 1.29 KB
/
LeetCode-278-First-Bad-Version.java
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
40
41
42
43
44
45
46
47
/*
LeetCode: https://leetcode.com/problems/first-bad-version/
LintCode: http://www.lintcode.com/problem/first-bad-version/
JiuZhang: http://www.jiuzhang.com/solutions/first-bad-version/
ProgramCreek: not find
Other: http://www.cnblogs.com/yuzhangcmu/p/4161837.html
Analysis:
Binary Search
Time O(logN)
*/
/* The isBadVersion API is defined in the parent class VersionControl.
boolean isBadVersion(int version); */
public class Solution extends VersionControl {
// // 1.Binary Search
// public int firstBadVersion(int n) {
// if(n == 0) return 0;
// if(n == 1) if(isBadVersion(n)) return n;
// int lo = 1, hi = n;
// while(lo + 1 < hi){
// int mid = lo + (hi - lo) / 2;
// if(isBadVersion(mid)) hi = mid;
// else lo = mid;
// }
// if(isBadVersion(lo)) return lo;
// return hi;
// }
// 2.Binary Search(simpler)
public int firstBadVersion(int n) {
if(n == 0) return 0;
if(n == 1) if(isBadVersion(n)) return n;
int lo = 1, hi = n;
while(lo < hi){
int mid = lo + (hi - lo) / 2;
if(isBadVersion(mid)) hi = mid;
else lo = mid + 1; //here lo = mid + 1
}
return hi;
}
}