Skip to content

Commit 3a0c211

Browse files
Lintcode/src/chapter2_binary_search/FirstBadVersion.java
1 parent 885b065 commit 3a0c211

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package chapter2_binary_search;
2+
3+
public class FirstBadVersion {
4+
5+
private static class SVNRepo{
6+
//this is a fake method to make this class happy in Eclipse.
7+
public static boolean isBadVersion(int n){
8+
return false;
9+
}
10+
}
11+
12+
/**
13+
* @param n: An integers.
14+
* @return: An integer which is the first bad version.
15+
*/
16+
public int findFirstBadVersion_solution1(int n) {
17+
// write your code here
18+
if (n == 1) return n;
19+
int left = 1, right = n;
20+
while(left+1 < right){
21+
int mid = left + (right-left)/2;
22+
if(!SVNRepo.isBadVersion(mid)) left = mid;
23+
else right = mid;
24+
}
25+
if(SVNRepo.isBadVersion(left)) return left;
26+
return right;
27+
}
28+
29+
public int findFirstBadVersion_solution2(int n) {
30+
// write your code here
31+
int left = 1, right = n;
32+
while(left+1 < right){
33+
int mid = left + (right-left)/2;
34+
if(!SVNRepo.isBadVersion(mid)) left = mid;
35+
else right = mid;
36+
}
37+
if(left != right){
38+
if(!SVNRepo.isBadVersion(left)){
39+
if(SVNRepo.isBadVersion(right)) return right;
40+
else return -1;
41+
} else return left;
42+
}
43+
if(SVNRepo.isBadVersion(left)) return left;
44+
return -1;
45+
}
46+
47+
48+
}

0 commit comments

Comments
 (0)