278. First Bad Version

来源:互联网 发布:手机火车票订票软件 编辑:程序博客网 时间:2024/04/19 10:22

题目:

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.


题意:

你是一个产品经理,当前正领导着一个团队开发一个新产品。不幸的是,这个新产品最近的版本在质量检查的的失败了。每个版本都是基于前一个版本的基础上开发的,一个失败的版本之后的所有版本都是坏的。有n个版本号,想找到第一个失败的版本,它导致了后面所有的版本错误。给定bool isBadVersion(version)函数,该函数返回该版本是否是失败的版本。实现一个功能去找到第一个失败的版本,并且尽可能少的调用提供的API。


思路:

由于版本号是从1开始,一直到n,属于增序排列,因此可以采用二分查找的策略,减少比较次数。需要注意的是,在取二分查找的中间值时,不要使用左右相加后再除以2的方式,这样可能会在计算时产生溢出

代码:20ms

/* The isBadVersion API is defined in the parent class VersionControl.      boolean isBadVersion(int version); */public class Solution extends VersionControl {    public int firstBadVersion(int n) {        if (n <= 0) return 0;                if (isBadVersion(1)) {            return 1;        } else if (!isBadVersion(n)) {            return Integer.MAX_VALUE;        }                int left = 1;        int right = n;                int mid;        while (true) {            mid = left + (right - left) / 2;            if (mid == left) {                return right;            }            if (isBadVersion(mid)) {                right = mid;            } else {                left = mid;            }        }    }}
另一版本:C++版:0ms

// Forward declaration of isBadVersion API.bool isBadVersion(int version);class Solution {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;    }};

0 0
原创粉丝点击