183.First Bad Version
题目:
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.
假设您有n个版本[1,2,...,n]并且您想找出第一个坏的版本,这会导致以下所有版本都不好。
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.
您将获得一个API bool isBadVersion(版本),它将返回版本是否错误。 实现一个函数来查找第一个坏版本。 您应该最小化对API的调用次数。
Example:
Given n = 5, and version = 4 is the first bad version.
给定n = 5,版本= 4是第一个坏版本。call isBadVersion(3) -> false call isBadVersion(5) -> true call isBadVersion(4) -> true Then 4 is the first bad version.
解答:
1 /* The isBadVersion API is defined in the parent class VersionControl. 2 boolean isBadVersion(int version); */ 3 4 public class Solution extends VersionControl { 5 public int firstBadVersion(int n) { 6 int left=1,right=n; 7 while(left<right){ 8 int mid=left+(right-left)/2; 9 if(isBadVersion(mid)) right=mid; 10 else left=mid+1; 11 } 12 return left; 13 } 14 }
详解:
显然二分查找法