letecode [278] - First Bad Version

假装没事ソ 提交于 2020-03-17 01:03:55

 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.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true

Then 4 is the first bad version. 

题目大意

  给定一个数字n(某项目的n个版本)和一个接口(判断某个版本是否出错),找到第一个出错的版本。要求调用接口的次数尽可能少。

理  解:

  采用二分法减少查找时间。第一个出错版本满足:它的检查函数返回true,它前面一个版本检查函数返回false。

  若当前版本为false说明第一个出错版本在右边,更新left;若当前版本的前一个版本为true说明第一个出错版本在左边。

代 码 C++:

// Forward declaration of isBadVersion API.
bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left=1,right=n;
        int mid = 1;
        while(left<=right){
            mid = (right-left)/2 + left;
            if(isBadVersion(mid)){
                if(!isBadVersion(mid-1))
                    return mid;
                right = mid - 1;
            }else{
                left = mid + 1;
            }
        }
        return mid;
    }
};

运行结果:

  执行用时 :4 ms, 在所有C++提交中击败了92.69% 的用户

  内存消耗 :8.2 MB, 在所有C++提交中击败了6.82%的用户
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!