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的基本知识。