First Bad Version

题目名称
First Bad Version—LeetCode链接

描述
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.

分析
  这道题是典型的二分查找,先确定好中间节点为当前查找节点,需要在搜索过程中加一个判断:如果当前查找的节点为BadVersion,则需要判断前一个节点是否为BadVersion,如果是则继续往前二分查找,如果不是,返回当前节点。
  如果当前节点不是BadVersion,则需要判断后一个节点是否为BadVersion,如果是,则返回后一个节点,如果不是则继续往后二分查找。
  如果没有找到,则返回0。

C++代码

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

class Solution {
public:
    int firstBadVersion(int n) {
        int min=1,max=n;
        int mid;
        while(min<=max){
            //中间节点的计算不可用(min+max)/2,会溢出
            mid = min+(max-min)/2;
            if(isBadVersion(mid)){
                if(mid-1>0 && !isBadVersion(mid-1))
                    return mid;
                else
                    max = mid-1;
            }
            else{
                if(mid+1<n && isBadVersion(mid+1))
                    return mid+1;
                else
                    min = mid+1;
            }
        }
        if(isBadVersion(mid))
            return mid;
        else 
            return 0;
    }
};

总结
  这道题一开始计算中间节点用mid=(min+max)/2,提交时报错Time Limit Exceeded,后来改成mid = min+(max-min)/2之后就Accept,猜想可能是溢出问题。

你可能感兴趣的:(LeetCode,二分查找,二分搜索)