In general, you can find the K largest (or smallest) numbers in the array using one pass for any K. The total time complexity will be O (NK), where N is the size of the array:
Keep a sorted list of numbers that contains no more than K elements. Go through the array and for each element:
- If the list is not already filled, insert an element
- otherwise, if the item is larger than the smallest item in the list, insert that item and delete the smallest.
At the end, the list will contain the K largest elements that we wanted.
This solution is rather slow. Using a self-balancing binary search tree or a skip list, you can go to O (N log K). (Since it is generally impossible to sort faster than O (N log N), and this method can be used to sort the entire array, if we set K = N, it looks like the best we can get.)
In the case of K = 2, you do not need all this heavy equipment. Two variables are enough, representing two positions in the list.
svick
source share