zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】查找与排序题10:First Bad Version

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    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.
    Example:
    Given n = 5, and version = 4 is the first bad version.
     
    call isBadVersion(3) -> false
    call isBadVersion(5) -> true
    call isBadVersion(4) -> true
     
    Then 4 is the first bad version.

    C++
     
    // Forward declaration of isBadVersion API.
    bool isBadVersion(int version);
    //序列可看成(0,0,0,0,1,1,1,1,1,1,1,1,1,1)找第一个为1的数(可用lower_bound函数)
    class Solution
    {
    public:
        int firstBadVersion(int n) //版本序列为有序序列,可用二分查找
        {
            int left = 1,mid,right=n;
            while(left<=right) //这里也可以写成<
            {
                mid = left + (right - left)/2; //防止(left+right)/2造成溢出风险
                if(!isBadVersion(mid))
                {
                    left = mid + 1; //为0时往右边找,left会移动到第一个为1的数的位置
                }
                else
                {
                    right = mid - 1;//为1时往左边找,也可以写成right=mid
                }
            }
           
            if(isBadVersion(left)) return left;
            else return -1; //如果找不到就返回-1
           
        }
    };
    /*
        //一般的二分查找
            while(left <= right) //注意这里为<=,因为要计算一次mid再返回
            {
                mid = left + (right - left)/2; //防止(left+right)/2造成溢出风险
                if(a[mid]<key)
                {
                    left = mid + 1;
                }
                else if(a[mid]>key)
                {
                    right = mid -1;
                }
                else
                {
                    return mid;
                }
            }
           
    */
     
  • 相关阅读:
    我对Web开发相关技术的认识过程
    JavaScript、JSP和Java之间的关系
    中断处理中的save_all、restore_all和iret
    实验五:Linux操作系统是如何工作的?破解操作系统的奥秘
    java CPU的乱序执行
    java缓存行对齐(缓存行二)
    解决ojdbc6升级ojdbc8中文乱码问题
    Caused by: java.lang.ClassNotFoundException: com.alibaba.dubbo.common.Version
    springSecurity5 重定向登录页面后 报错:尝试清除 Cookie.net::ERR_TOO_MANY_REDIRECTS status:200
    java 工厂模式 从无到有-到简单工厂模式-到工厂方法模式-抽象工厂模式
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225954.html
Copyright © 2011-2022 走看看