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.

    思路:二分查找。

    要注意的一点是,在计算中间点 mid的值时,如果用mid = (left + right) >> 1有可能结果会溢出。

    这里用 mid = (left >> 1) + (right >> 1)

    式子中后面如果不加括号有可能会出错,因为会把right的值当成前面left的位移操作的距离。

     1 // Forward declaration of isBadVersion API.
     2 bool isBadVersion(int version);
     3 
     4 class Solution {
     5 public:
     6     int firstBadVersion(int n) {
     7         if (n < 2) return n;
     8         int left = 1, right = n;
     9         while ( left < right)
    10         {
    11             int mid = (left >> 1) + (right >> 1);
    12             bool bad = isBadVersion(mid);
    13             if (bad)
    14             {
    15                 if (mid == 1 || !isBadVersion(mid - 1))
    16                     return mid;
    17                 right = mid;
    18             }
    19             else
    20             {
    21                 if (isBadVersion(mid + 1))
    22                     return mid + 1;
    23                 left = mid + 1;
    24             }
    25         }
    26         return 0;
    27     }
    28 };
  • 相关阅读:
    排序预处理的思想
    枚举
    math细节
    physics 衍射和ganshe
    hearing speaking words
    appium的环境安装
    基于ASP.NET MVC 4.0的音乐商店全套项目教程
    WPF/WinForm 关于窗体大小变化的消息机制处理
    用WPF搭建自己的万能播放器(C#)前篇
    VS2010网站发布到服务器上
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4910168.html
Copyright © 2011-2022 走看看