zoukankan      html  css  js  c++  java
  • 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更长

  • 相关阅读:
    [IOI1994][USACO1.5]数字三角形 Number Triangles
    和为给定数
    小凯的疑惑
    棋盘
    【2020NOI.AC省选模拟#2】C. 送分题
    【NOI OL #2】涂色游戏
    【NOI OL #3】小结
    【NOI OL #1】最小环
    【NOI OL #1】冒泡排序
    【NOI OL #1】序列
  • 原文地址:https://www.cnblogs.com/luckygxf/p/4923489.html
Copyright © 2011-2022 走看看