3 ms·
high level: you keep track of the K largest elements (call this array A). Every time you read an element (call it x), you compare it to the smallest element in
by veyron 15y ago
high level: you keep track of the K largest elements (call this array A). Every time you read an element (call it x), you compare it to the smallest element in A. if x is bigger than the smallest element of A, then remove the smallest element from A and add x to the list (and sort).
There are N elements in the sequence, and you can arrange for the sorting to be a single-step bubble sort, so that the total cost is O(K) operations per element --> O(NK) overall. Noting that K is constant, it's O(N).
Note that this really assumes K is constant. If K is depends on N, then the array A will expand