leetcode_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.
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.

思路:

可以用二分查找的思路来解决,当mid所在的位置为badVersion时,则mid所在的位置可能为第一个badVersion,所以置end=mid;当mid所在的位置不是badVersion时,说明badVersion只可能在mid后,置start=mid+1,直到start>=end时,start所在的位置就是badVersion所在位置了。

代码:

public int firstBadVersion(int n) {
        //Solution solution=new Solution();
        int start=1,end=n,mid=0;
        while(start<end)
        {
            mid=(end-start)/2+start;
            if(isBadVersion(mid))
            {
                end=mid;
            }
            else
            {
                start=mid+1;
            }
        }
        return start;
    }


你可能感兴趣的:(leetcode_First Bad Version)