sundeepblue
4/13/2014 - 5:43 PM

Find the largest k numbers in an enormous array of numbers. You cannot sort the array.

Find the largest k numbers in an enormous array of numbers. You cannot sort the array.

// find largest k, should use min heap
// if find smallest k, should use max heap

vector<int> find_largest_k_numbers(vector<int>& A, int K) {
    vector<int> res;
    
    if(A.empty() || K == 0 || K > A.size()) return res;
    if(K == A.size()) return A;
    
    // note, the default STL priority_queue is a max heap declared as:
    // priority_queue<int, vector<int>, less<int>> max_heap;
    
    priority_queue<int, vector<int>, greater<int>> min_heap; 
    for(int i=0; i<K; ++i) {
        min_heap.push(A[i]);
    }
    for(int i=K; i<A.size(); ++i) {
        if(A[i] > min_heap.top()) {
            min_heap.pop();
            min_heap.push(A[i]);
        }
    }
    for(int d : min_heap)
        res.push_back(d);
    
    return res;
}