How to find second largest number in a list?

前端 未结 14 1957
遇见更好的自我
遇见更好的自我 2020-12-06 15:38

So I have to find the second largest number from list. I am doing it through simple loops.

My approach is to divide a list into two parts and then find the largest n

14条回答
  •  时光取名叫无心
    2020-12-06 15:49

    O(n^2) algorithm:

    In [79]: alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    
    In [80]: max(n for n in alist if n!=max(alist))
    Out[80]: 100
    

    O(n) algorithm:

    In [81]: alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    
    In [82]: M = max(alist)
    
    In [83]: max(n for n in alist if n!=M)
    Out[83]: 100
    

提交回复
热议问题