File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Lintcode/src/chapter2_binary_search Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments