Python面试题:求列表当中最大的三个元素

95 阅读1分钟
在牛客网
https://www.nowcoder.com/
上刷题遇到如何从

list

中取得最大的三个值:自己写的方法复杂度太高,放上大牛的方法,复杂度很低。看了好几遍才体会到大概的精髓。


[Python]
纯文本查看
复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'''
从list中取出最大的三个值
__author__:无名
'''
def FindList3MaxNum(foo):
max1, max2, max3 = None, None, None
for num in foo:
if max1 is None or max1 < num:
max1, num = num, max1
if num is None:
continue
if max2 is None or num > max2:
max2, num = num, max2
if num is None:
continue
if max3 is None or num > max3:
max3 = num
return max1, max2, max3
if __name__ == '__main__':
foo = [78, 23, 10, 56, 4, 103, 89, 14]
max1, max2, max3 = FindList3MaxNum(foo)
print(max1, max2, max3)