• 【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;
        }
    }
  • 相关阅读:
    Django 用户认证(Auth)组件
    Django 中间件
    EFCore Map 2 entities to same table
    Prevent properties being loaded unless specifically requested
    AutoMapper Queryable Extensions
    What does Include() do in LINQ?
    SqlServer备份还原 出现操作系统错误 5(拒绝访问) 的解决方案
    When to use Include in EF? Not needed in projection?
    Evaluate: lim x → 0 [1/x^2 1/sin^2x] 高等数学
    AutoMapper Explicit expansion
  • 原文地址:https://www.cnblogs.com/puyangsky/p/6547891.html
Copyright © 2020-2023  润新知