zoukankan      html  css  js  c++  java
  • 【Leetcode】278. 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.

    题意是有一个数组,某个数之后调用isBadVersion都会返回true,找到这个数的位置。

    思路

    典型的二分查找,需要注意的是右边界向mid靠拢时不用减一,因为要求返回的是第一个开始变化的位置。

    另外,开始使用

    mid = (left + right) / 2
    

    总是会TLE,但是用

    mid = left + (right - left) / 2
    

    就没问题,原因是left+right可能超过了INT_MAX。另外可以使用

    mid = (left + right) >>> 1
    

    这种方式,因为是无符号的右移1位。

    挺有意思的一题,以后写二分查找时确定mid一定要谨记。

    代码

    /**
     * Author: puyangsky
     * Date: 17/3/14
     * Complexity: Time O(logN) Space O(1)
     * Method: 二分查找
     */
    public class L278 {
        public boolean isBadVersion(int version) {
            return true;
        }
        public int firstBadVersion(int n) {
            int left = 1, right = n;
            while (left < right) {
    //            int mid = (left + right) >>> 1;
                int mid = left + (right - left) / 2;
                //如果中位数为bad,则中位数右边都为bad
                if(isBadVersion(mid)) right = mid;
                else left = mid + 1;
            }
            return left;
        }
    }
  • 相关阅读:
    ionic 刷新页面的几种方法
    Highcharts中如何外部修改pointStart
    前端分页 思路
    快捷选时间
    获取今天,昨天,本周,上周,本月,上月时间
    angularjs 弹出框 $modal
    SQL 查找存在某内容的存储过程都有哪些
    LINQ to SQL和Entity Framework
    SQL模糊查询条件的四种匹配模式
    数据库--中文表名及字段名的优缺点
  • 原文地址:https://www.cnblogs.com/puyangsky/p/6547891.html
Copyright © 2011-2022 走看看