[letecode java] First Bad Version

来源:互联网 发布:英语口语app软件 编辑:程序博客网 时间:2024/06/14 22:49

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.

这个题目很简单,采用二分查找即可解决,唯一一个问题就是超时,超时的原因在于int型整数越界,遇到过这种问题的人自然不会有问题,第一次遇到的话挺烦人,特别是没用eclipse调试的话。所以,以后二分查找最好用medium=begin+(end-begin)/2;而不是medium=(begin+end)/2。

代码如下:

/* 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 -1;
        int begin=1,end=n;
        int medium=0;
        int result=n;
        while(begin+1<end){
            medium=begin+(end-begin)/2;
            //medium=(begin+end)/2; int型整数会出现越界问题
            if(isBadVersion(medium))
               end=medium;
            else
               begin=medium;
        }
         if (isBadVersion(begin)) 
            return begin;
         else 
            return end;
        
    }
}

0 0