[Hash table and heap] Lintcode 545. Top K large numbers II

Lintcode 545. Top K Large Numbers II

Title description: Implement a data structure and provide the following two interfaces

  1. add(number) add an element
  2. topk() returns the top K number

Insert picture description here
Insert picture description here
The code uses priority_queue to store the largest number of K to achieve:

bool cmp(const int &a, const int &b) {
    
    
        return a > b;
    }

class Solution {
    
    
private:
    priority_queue<int, vector<int>, greater<int>> queue;
    int k;
    
public:
    /*
    * @param k: An integer
    */Solution(int k) {
    
    
        this->k = k;
    }

    /*
     * @param num: Number to be added
     * @return: nothing
     */
    void add(int num) {
    
    
        if (k > queue.size()) {
    
    
            queue.push(num);
        } else if (num > queue.top()){
    
    
            queue.pop();
            queue.push(num);
        }
    }

    /*
     * @return: Top k element
     */
    vector<int> topk() {
    
    
        vector<int> topk;
        int n = queue.size();
        for (int i = 0; i < k && i < n; ++i) {
    
    
            topk.push_back(queue.top());
            queue.pop();
        }
        for (int i = 0; i < n; ++i) {
    
    
            queue.push(topk[i]);
        }
        sort(topk.begin(), topk.end(), cmp);
        return topk;
    }
};

Guess you like

Origin blog.csdn.net/phdongou/article/details/113923871