Skip to content

Commit 8c84804

Browse files
refactor 278
1 parent 7ee0e55 commit 8c84804

File tree

1 file changed

+33
-26
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+33
-26
lines changed
Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,44 @@
11
package com.fishercoder.solutions;
22

3-
/**You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
4-
5-
Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.
6-
7-
You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.*/
3+
/**
4+
* 278. First Bad Version
5+
*
6+
* You are a product manager and currently leading a team to develop a new product.
7+
* Unfortunately, the latest version of your product fails the quality check.
8+
* Since each version is developed based on the previous version, all the versions after a bad version are also bad.
9+
* Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
10+
* which causes all the following ones to be bad.
11+
*
12+
* You are given an API bool isBadVersion(version) which will return whether version is bad.
13+
* Implement a function to find the first bad version. You should minimize the number of calls to the API.*/
814
public class _278 {
915

10-
public int firstBadVersion(int n) {
11-
int left = 1;
12-
int right = n;
13-
if (isBadVersion(left)) {
14-
return left;
15-
}
16+
public static class Solution1 {
17+
public int firstBadVersion(int n) {
18+
int left = 1;
19+
int right = n;
20+
if (isBadVersion(left)) {
21+
return left;
22+
}
1623

17-
while (left + 1 < right) {
18-
int mid = left + (right - left) / 2;
19-
if (isBadVersion(mid)) {
20-
right = mid;
21-
} else {
22-
left = mid;
24+
while (left + 1 < right) {
25+
int mid = left + (right - left) / 2;
26+
if (isBadVersion(mid)) {
27+
right = mid;
28+
} else {
29+
left = mid;
30+
}
2331
}
24-
}
2532

26-
if (isBadVersion(left)) {
27-
return left;
33+
if (isBadVersion(left)) {
34+
return left;
35+
}
36+
return right;
2837
}
29-
return right;
30-
}
3138

32-
private boolean isBadVersion(int left) {
33-
//this is a fake method to make Eclipse happy
34-
return false;
39+
private boolean isBadVersion(int left) {
40+
//this is a fake method to make Eclipse happy
41+
return false;
42+
}
3543
}
36-
3744
}

0 commit comments

Comments
 (0)