二分查找May-1th “First Bad Version (Python3)”
Posted 迪乐阅读
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找May-1th “First Bad Version (Python3)”相关的知识,希望对你有一定的参考价值。
n
versions
[1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
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.
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)”的主要内容,如果未能解决你的问题,请参考以下文章