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.

思路:

这道题很明显用二分查找,使用二分查找后。但输入n = 2126753390,firstBadVersion = 1702766719后,一直超时,后面用Eclipse调试的时候发现,是大数相加溢出造成的。改用long后accept

P.S.注意溢出

 1 /* The isBadVersion API is defined in the parent class VersionControl.
 2       boolean isBadVersion(int version); */
 3 
 4 public class Solution extends VersionControl {
 5     public int firstBadVersion(int n) {
 6         long low = 1;
 7         long high = n;
 8         long middle = 0;
 9         while(low <= high){
10             middle = (low + high) / 2;
11             if(isBadVersion((int)middle)){
12                 if(middle == 1 || !isBadVersion((int)middle - 1))
13                     return (int)middle;
14                 else
15                     high = middle - 1;
16             }//if
17             else
18                 low = middle + 1;
19         }//while
20         
21         return -1;
22     }
23 }

 在讨论区看到有解决溢出问题的,没有用long。我觉得很漂亮

1 middle = low + (high - low) / 2;

P.S.但这尼玛跑的速度居然比用long更长

posted on 2015-10-30 15:48  luckygxf  阅读(190)  评论(0编辑  收藏  举报

导航