zoukankan      html  css  js  c++  java
  • [leetcode] 278. 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.

    我的代码如下:

     1 // Forward declaration of isBadVersion API.
     2 bool isBadVersion(int version);
     3 
     4 class Solution {
     5 public:
     6     int firstBadVersion(int n) {
     7         if (isBadVersion(1)) return 1;
     8         int left = 1, right = n, mid = (1 + n) / 2;
     9         while (left < right) {
    10             mid = left + (right - left) / 2;
    11             if (isBadVersion(mid)) right = mid;
    12             else left = mid + 1;
    13         }
    14         return left;
    15     }
    16 };

    一开始我一直把第10行写为

    mid = (left + right) / 2;

    但是一直超时,后来搜了一下发现 因为(left + right) 有可能会溢出导致不断循环。

    但是有一个困惑并没有找到原因:

    把第10行换到else下边就会超时。。。希望能有人解惑。

  • 相关阅读:
    Wayland中的跨进程过程调用浅析
    设计模式总结
    C语言---整型字符串转换
    抽象工厂模式
    SVNclient安装与使用
    [置顶] MyEclipse下安装插件方法(properties文件编辑器Propedit为例)
    脑筋急转弯的歧义性
    脑筋急转弯的歧义性
    从和式积分到定积分
    从和式积分到定积分
  • 原文地址:https://www.cnblogs.com/zmj97/p/7502635.html
Copyright © 2011-2022 走看看