278. First Bad Version
二分法,如果isBadVersion返回true则坏版本在左边,right = mid,否则 left = mid + 1。
注意溢出问题 left+(right - left) /2
最后return left right均可
/* 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; while(left < right){ int mid = left + (right - left) / 2; if(isBadVersion(mid)) right = mid; else left = mid + 1; } return left; } }
原文:https://www.cnblogs.com/Afei-1123/p/11785610.html