题目
思路
用dict存{ 数值: 出现的次数 },定义一个自定义的降序顺序数组 [1, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2],两层遍历找符合条件的a,b。第一次符合的即为最大的葫芦。
代码
def solution(n, max, array):
# Edit your code here
arr = [1, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
num_count = {}
for num in array:
if num_count.get(num) is None:
num_count[num] = 1
else:
num_count[num] += 1
for a in arr:
a_count = num_count.get(a)
if (a_count is not None and a_count >= 3):
for b in arr:
if a == b:
continue
b_count = num_count.get(b)
if (b_count is not None and b_count >= 2):
total = a * 3 + b * 2
if (total <= max):
return [a, b]
return [0, 0]
if __name__ == "__main__":
# Add your test cases here
print(solution(9, 34, [6, 6, 6, 8, 8, 8, 5, 5, 1]) == [8, 5])
print(solution(9, 37, [9, 9, 9, 9, 6, 6, 6, 6, 13]) == [6, 9])
print(solution(9, 40, [1, 11, 13, 12, 7, 8, 11, 5, 6]) == [0, 0])
复杂度
-
时间复杂度
dict记录 O(N),两层for循环 O(n²),取最大系数即
O(n²) -
空间复杂度
O(n)
学到了
python中遍历dict键的方法:
my_dict = {'a': 1, 'b': 2, 'c': 3}
for key in my_dict:
print(key)
for key in my_dict.keys():
print(key)
for key, value in my_dict.items():
print(key)
python中没有===(严格相等运算符),比较地址使用is:
a = [1, 2]
b = [1, 2]
print(a == b) # 比较的是值 True
print(a is b) # 比较的是地址 False