二分查找May-1th “First Bad Version (Python3)”

Posted 迪乐阅读

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找May-1th “First Bad Version (Python3)”相关的知识,希望对你有一定的参考价值。


 五月,总结模板的日子.

Day 1  ——   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. 


解题思路


典型二分法

  • 没啥好说的,典型二分法~

# The isBadVersion API is already defined for you.# @param version, an integer# @return a bool# def isBadVersion(version):
class Solution: def firstBadVersion(self, n): """ :type n: int :rtype: int """ hi = n lo = 1
while lo <= hi:            crr = (hi + lo) // 2 if isBadVersion(crr): hi = crr - 1 else: lo = crr + 1
return lo

时间复杂度O(logn),空间复杂度O(1)。


二分查找有序list

  • 典型二分查找模板,很多题目都可由其变换而来~

def binary_search(list,item): low = 0 high = len(list) - 1 while low <= high: mid = int((low + high) / 2) guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1
my_list = [0,1,3,6,9]print(binary_search(my_list,3))





以上是关于二分查找May-1th “First Bad Version (Python3)”的主要内容,如果未能解决你的问题,请参考以下文章

Task 04:数组二分查找

异序二分查找 二分查找方程根 二分查找重复元素最后一个

每周算法小知识之二分查找

查找算法之“二分查找”

java 二分查找法

hiho36 二分·二分查找二分查找