Leetcode 278. First Bad Version

来源:互联网 发布:g71编程实例 编辑:程序博客网 时间:2024/04/29 11:08

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question
你是一个产品经理,现在带领一个团队跟进一个新的产品。不幸的是,最新版本的产品质量检测失败了。每一个版本都是在上一个版本的基础上发展而来的 ,在一个质量不过关的版本以后的所有版本质量都是不过关的。
假设你有n个版本[1,2,…,n],同时 你想找出第一个坏的版本,导致接下来的版本都坏了。
给你一个api bool isBadVersion(version) 返回版本是否是坏的。 实现一个函数找出第一个坏的版本,你应该最小化调用api的次数。

解法:利用二分法判断即可找到第一个坏的版本。

public class Solution extends VersionControl {    public int firstBadVersion(int n) {        int min = 1, max = n, mid = 0;        while(min <= max){            mid = min + (max - min) / 2;            if(isBadVersion(mid)){                max = mid - 1;            } else {                min = mid + 1;            }        }        return min;    }} 
0 0
原创粉丝点击