binary search 2

本文介绍了如何使用二分查找算法解决产品管理中找出第一个导致所有后续版本质量不合格的问题。通过Python3和C两种语言实现firstBadVersion函数,最小化调用API次数来确定首个不良版本。此外,还回顾了二叉树相关知识,增强了Python3和C语言的技能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2022-09-10
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.
在这里插入图片描述

解题方法:
1、python3

# The isBadVersion API is already defined for you.
# def isBadVersion(version: int) -> bool:

class Solution:
    def firstBadVersion_v1(self, n: int) -> int:
        l, r = 1, n
        result = 0
        while l <= r:
            m = (l+r) // 2
            if isBadVersion(m):
                result = m
                r = m-1
            else:
                l = m+1
        return result
    
    def firstBadVersion_v2(self, n: int) -> int:
        low = 1
        high = n
        flag = n
        if isBadVersion(low):
            return 1
        for i in range(high):
            mid = int((low + high) / 2)
            if isBadVersion(mid) == False:
                if mid == flag - 1:
                    return flag
                low = mid + 1
            else:
                flag = mid
                high = mid- 1

2、C

// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

int firstBadVersion(int n) {
    int left = 1;
    int right = n;
    int flag = 0;
    while(left <= right){
        int mid = left + (right - left) / 2;
        if (isBadVersion(mid)){
            flag = mid;
            right = mid - 1;
        }
        else{
            left = mid + 1;
        }
    }
    return flag;
}

最后,浅放一下 runtime and memory 的对比吧
在这里插入图片描述

今日份继续刷二叉树,我感觉我熟悉了,我感觉我可以举一反三了,我感觉我可以直接手撕二叉树的大部分问题了,直接飘了;同时,进一步巩固了python3,也复习了c的基本知识。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值