|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
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.*/ |
8 | 14 | public class _278 {
|
9 | 15 |
|
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 | + } |
16 | 23 |
|
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 | + } |
23 | 31 | }
|
24 |
| - } |
25 | 32 |
|
26 |
| - if (isBadVersion(left)) { |
27 |
| - return left; |
| 33 | + if (isBadVersion(left)) { |
| 34 | + return left; |
| 35 | + } |
| 36 | + return right; |
28 | 37 | }
|
29 |
| - return right; |
30 |
| - } |
31 | 38 |
|
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 | + } |
35 | 43 | }
|
36 |
| - |
37 | 44 | }
|
0 commit comments