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 returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
说明:一个叫做isBadVersion(version) 的API给我们用,它可以用来检测一个版本是否可行。我们要找到一系列版本中第一个不好的版本(自从第一个不好的版本出现后,后面都不好了,之前都没事),比如:TTTTTFFFFFFFFFF, 表示从第6个版本开始出现的质量问题

思路:
二叉搜索,没啥说的
注意二叉搜索的几个问题:

  1. 搜索左侧区间时,设right=mid
  2. 搜索右侧区间时,设left=mid+1
  3. 求中点区间时用left+(right-left)/2可以避免整型越界

代码如下:

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left=1;
        int right=n;
        while(left<right){
            //int mid=(left+right)/2;
            int mid = left + (right - left) / 2;
            if(isBadVersion(mid)==true){
                right=mid;
            }
            else{
                left=mid+1;
            }
        }
        return left;
    }
}

时间复杂度: O(logn)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值