zoukankan      html  css  js  c++  java
  • LeetCode OJ: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.

    这个是简单的二分法,但是二分法的细节还是要注意一下。相当于从00000...11111中选出第一个1的。二分法的关键就是应该确保要找的值一定应该咋迭代的那个区间之中,比如这里的mid=1的时候,取end = mid, mid = 0的时候,start = mid + 1; 这样可以保证第一个1时钟在这个区间之中,追后可以得到第一个1.

    还有个细节就是mid不适合用(start + end)/2,这样有可能导致溢出的情况。

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

     二分法的简单变种而已,java版本代码如下所示:

     1 public class Solution extends VersionControl {
     2     public int firstBadVersion(int n) {
     3         int beg = 1;
     4         int end = n;
     5         while (beg <= end) {
     6               int mid = beg+(end-beg)/2;
     7               if(isBadVersion(mid)){
     8                   end = mid - 1;
     9               }else{
    10                   beg = mid + 1;
    11               }
    12         }
    13         return beg; //注意边界条件,为什么返回的是beg,因为beg加上1的时候判断正好不是坏的版本,加上变成第一个,end达不到这个效果
    14     }
    15 }
  • 相关阅读:
    BZOJ2095 [Poi2010]Bridges
    BZOJ3307 雨天的尾巴
    【CSP2020】 T3 动物园
    【CSP2020】 T1儒略日
    洛谷P3455 [POI2007]ZAP-Queries
    【黑科技学习】光速幂
    XJTUOJ #1023 JM的祖传零钱箱
    XJTUOJ #1168 zxh的后宫管理系统
    XJYUOJ #1053 nocriz与队列计算机
    XJTUOJ #1017 JM的完美集合
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4872513.html
Copyright © 2011-2022 走看看