題目大意:產品有5個版本1,2,3,4,5其中下一個版本依賴上一個版本,即版本4是壞的,5也就是壞的,如今要求哪一個版本是第一個壞的。code
思路:二分法,middle-1好,middle壞,middle就是第一個壞的版本ip
Java實現:leetcode
/* The isBadVersion API is defined in the parent class VersionControl. boolean isBadVersion(int version); */ public class Solution extends VersionControl { public int firstBadVersion(int n) { int left = 1, right = n; int badVersion = -1; while (badVersion == -1) { int middle = left + (right-left)/2; boolean pre = isBadVersion(middle-1); boolean cur = isBadVersion(middle); if (!pre && cur) { badVersion = middle; } else { // false true middle is BadVersion // false false left = middle + 1; // true false x // true true right = middle - 1; if (pre) { right = middle-1; } else { left = middle + 1; } } } return badVersion; } }
參考:get
public int firstBadVersion(int n) { int start = 1, end = n; while (start < end) { int mid = start + (end-start) / 2; if (!isBadVersion(mid)) start = mid + 1; else end = mid; } return start; }