Retrieve the two highest item from a list containing 100,000 integers

后端 未结 15 754
心在旅途
心在旅途 2020-12-13 17:55

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

15条回答
  •  时光说笑
    2020-12-13 18:17

    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]
    

提交回复
热议问题