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

  • 相关阅读:
    【nginx】常见的陷阱和错误
    linux配置文件的一些调优
    关于防刷票的一些问题
    关于nginx的限速模块
    使用Javascript监控前端相关数据
    【mysql】关于Index Condition Pushdown特性
    【mysql】关于临时表
    堆和栈的区别(转过无数次的文章)
    深入PHP内核之in_array
    【mysql】索引的优化
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4923489.html
Copyright © 2020-2023  润新知