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 };
  • 相关阅读:
    Oracle连接数过多释放机制
    Sql优化(三) 关于oracle的并发
    查询Oracle正在执行的sql语句
    odi增量更新策略
    如何查询Oracle性能监控
    Oratop工具——实时数据库性能监控工具
    Oracle超出最大连接数问题及解决
    oracle查看允许的最大连接数和当前连接数等信息
    八大算法思想
    面向切面编程的解释
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4910168.html
Copyright © 2011-2022 走看看