在牛客網https://www.nowcoder.com/上刷題遇到如何從list中取得最大的三個值:自己寫的方法複雜度太高,放上大牛的方法,複雜度很低。看了好幾遍才體會到大概的精髓。
''' 從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)