|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=278 lang=java |
| 3 | + * |
| 4 | + * [278] First Bad Version |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/first-bad-version/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Easy (28.99%) |
| 10 | + * Total Accepted: 215.1K |
| 11 | + * Total Submissions: 727.9K |
| 12 | + * Testcase Example: '5\n4' |
| 13 | + * |
| 14 | + * You are a product manager and currently leading a team to develop a new |
| 15 | + * product. Unfortunately, the latest version of your product fails the quality |
| 16 | + * check. Since each version is developed based on the previous version, all |
| 17 | + * the versions after a bad version are also bad. |
| 18 | + * |
| 19 | + * Suppose you have n versions [1, 2, ..., n] and you want to find out the |
| 20 | + * first bad one, which causes all the following ones to be bad. |
| 21 | + * |
| 22 | + * You are given an API bool isBadVersion(version) which will return whether |
| 23 | + * version is bad. Implement a function to find the first bad version. You |
| 24 | + * should minimize the number of calls to the API. |
| 25 | + * |
| 26 | + * Example: |
| 27 | + * |
| 28 | + * |
| 29 | + * Given n = 5, and version = 4 is the first bad version. |
| 30 | + * |
| 31 | + * call isBadVersion(3) -> false |
| 32 | + * call isBadVersion(5) -> true |
| 33 | + * call isBadVersion(4) -> true |
| 34 | + * |
| 35 | + * Then 4 is the first bad version. |
| 36 | + * |
| 37 | + */ |
| 38 | +/* The isBadVersion API is defined in the parent class VersionControl. |
| 39 | + boolean isBadVersion(int version); */ |
| 40 | + |
| 41 | +public class Solution extends VersionControl { |
| 42 | + public int firstBadVersion(int n) { |
| 43 | + int left = 1; |
| 44 | + int right = n; |
| 45 | + |
| 46 | + while (left < right) { |
| 47 | + int mid = left + (right - left) / 2; |
| 48 | + if (isBadVersion(mid)) { |
| 49 | + right = mid; |
| 50 | + } else { |
| 51 | + left = mid + 1; |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return left; |
| 56 | + } |
| 57 | +} |
| 58 | + |
0 commit comments