How can retrieve the two highest item from a list containing 100,000 integers without having to sort the entire list first?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to toggle on Order in ReactJS
- How to get the background from multiple images by
- PHP Recursively File Folder Scan Sorted by Modific
Iterating through the entire list is the only way to do it without sorting.
The best time you can expect is linear, since you have to at least look through all the elements.
Here is my pseudocode to solve the problem:
Copy your
List
toList_copy
. Retrieve the highest value and get its position by:Assign
0
to theHighest_value
.And run your line again.
Another solution that uses only base Python functions can be seen below:
If we split a list around its largest number, we know that the second largest number is either in the left half or the right half. So, we can trivially find the second largest number by simply finding the larger of the largest number in the left and right half of the list.
It's trivial to show this is O(n) time and O(1) space. We traverse the list once to find the largest element, then again to find the second largest. We only store the largest values themselves and the index of the largest value.
Sort the list, and if list is not null, extract last two element
Simple and most efficient:)
Now if sorting is not required, find max, remove max, find max again
Of course, you will lose the original list but you can create a temporary list as well.
In Python, use
heapq.nlargest
. This is the most flexible approach in case you ever want to handle more than just the top two elements.Here's an example.
Documentation: http://docs.python.org/library/heapq.html#heapq.nlargest