• 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更长

  • 相关阅读:
    JavaScript遍历表单元素
    JavaScript实现按钮改变网页背景色
    JavaScript实现指定格式字符串表单校验
    jQuery实现数字时钟
    Python使用递归绘制谢尔宾斯基三角形
    Python使用函数模拟“汉诺塔”过程
    Python使用函数实现杨辉三角
    CSS简单样式练习(七)
    CSS简单样式练习(六)
    cstring to char *例子
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4923489.html
Copyright © 2020-2023  润新知