forked from terrytong0876/LintCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFirst Bad Version.java
More file actions
114 lines (90 loc) · 2.6 KB
/
First Bad Version.java
File metadata and controls
114 lines (90 loc) · 2.6 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
M
Binary Search
根据isBadVersion的性质,判断还如何end=mid or start=mid.
isBadVersion 是有方向的嘛,一个点错了,后面全错。
```
/*
The code base version is an integer start from 1 to n.
One day, someone committed a bad version in the code case,
so it caused this version and the following versions are all failed in the unit tests.
Find the first bad version.
You can call isBadVersion to help you determine which version is the first bad one.
The details interface can be found in the code's annotation part.
Example
Given n = 5:
isBadVersion(3) -> false
isBadVersion(5) -> true
isBadVersion(4) -> true
Here we are 100% sure that the 4th version is the first bad version.
Note
Please read the annotation in code area to get the correct way to call isBadVersion in different language.
For example, Java is SVNRepo.isBadVersion(v)
Challenge
You should call isBadVersion as few as possible.
Tags Expand
Binary Search LintCode Copyright Facebook
*/
/*
Recap: 12.07.2015.
Feels like to find the 1st occurance of the match. going left all the way.
*/
/**
* public class SVNRepo {
* public static boolean isBadVersion(int k);
* }
* you can use SVNRepo.isBadVersion(k) to judge whether
* the kth code version is bad or not.
*/
class Solution {
public int findFirstBadVersion(int n) {
if (n < 1) {
return 0;
}
int start = 1;
int end = n;
int mid;
while (start + 1 < end) {
mid = start + (end - start)/2;
if (SVNRepo.isBadVersion(mid)) {
if (mid - 1 >= 1 && SVNRepo.isBadVersion(mid - 1)) {
end = mid;
} else {
return mid;
}
} else {
start = mid;
}
}
if (SVNRepo.isBadVersion(start)) {
return start;
}
return end;
}
}
class Solution {
/**
* @param n: An integers.
* @return: An integer which is the first bad version.
*/
public int findFirstBadVersion(int n) {
int start = 1;
int end = n;
int mid;
while (start + 1 < end) {
mid = start + (end - start) / 2;
if (VersionControl.isBadVersion(mid)) {
end = mid;
} else {
start = mid;
}
}//end while
if (VersionControl.isBadVersion(start)) {
return start;
} else if (VersionControl.isBadVersion(end)) {
return end;
} else {
return 0;
}
}
}
```