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

后端 未结 15 789
心在旅途
心在旅途 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:31

    A really slick way is to use heapq. Heapify the array (O(n)), then just pop an many elements that you need (log(n)). (Saw this question in an interview once, good question to keep in mind.)

提交回复
热议问题