How to find second largest number in a list?

前端 未结 14 1954
遇见更好的自我
遇见更好的自我 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条回答
  •  -上瘾入骨i
    2020-12-06 16:03

    O(n) solution

    alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
    m = alist[:2] #m will hold 2 values, fill it with the first two values of alist
    for num in alist:
        m = sorted(m + [num],reverse=True)[:2] #appends num to m and sorts it, takes only top 2
    m[1] #the second highest element.
    

    EDIT: changed to work with negative numbers. Basic description as follows

    First I set m to be the first two elements of alist. As I iterate through alist I will be adding one value to the end of m, then sorting the three elements and throwing away the smallest one. This ensures that at the end m will contain the top two largest elements.

提交回复
热议问题