题目 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.
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.
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. 思路 开发的一系列的版本,要找出第一个出错的版本。函数isBadVersion(version) 是返回version版本是有问题还是没有问题。使用二分法查找有一个注意的地方,不要溢出,同时注意if语句的返回处理情况。 主要还是用二分法查找的思想 代码
/* 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 low = 1; int high = n; int ver = 0; while (low < high) { ver = low + (high - low) / 2; //如果函数isBadVersion(ver)是真的,则说明是ver版本是有问题,那么第一个有问题是在ver之前 if (isBadVersion(ver)) { high = ver; } else { low = ver + 1; } } return low; } } 使用ver = low + (high - low) / 2;求中间值不会溢出,但是使用ver = (high +low) / 2就容易溢出。原题地址
