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 };
  • 相关阅读:
    axios 进行类库封装
    vue的中vuex为何需要mutation更新状态,vue-router的路由的理解
    发布订阅者模式、观察者模式总结
    es 模块的基础知识,深度了解
    绑定事件的模型
    rem+media+jquery布局结局方案
    VDOM总结
    react-redux
    发布网站配置文件和SSL
    css3d旋转
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4910168.html
Copyright © 2011-2022 走看看