Retrieve the two highest item from a list containi

2020-02-17 08:50发布

How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?

15条回答
▲ chillily
2楼-- · 2020-02-17 09:37

You iterate over the list, maintaining variables that contain the value of the highest and the second highest item encountered thus far. Each new item that is encountered will replace whichever of the two the new item is higher than (if any).

查看更多
我只想做你的唯一
3楼-- · 2020-02-17 09:37

Without sorting the list the only way to really do it is to iterate through the whole list and save the highest two numbers. I think you'd be better off sorting the list.

查看更多
【Aperson】
4楼-- · 2020-02-17 09:37

I know this topic is old, but here is a simple solution to this problem. Tested against heapq.nlargest and this is a bit faster (no sorting needed):

Works for both positive and negative numbers.

Function below: Max time used: 0.12, max memory used: 29290496 heapq.nlargest: Max time used: 0.14, max memory used: 31088640

def two_highest_numbers(list_to_work):

    first = None
    second = None

    for number in list_to_work:
        if first is None:
            first = number
        elif number > first:
            second = first
            first = number
        else:
            if second is None:
                second = number
            elif number > second:
                second = number

return [first, second]
查看更多
登录 后发表回答