703 - Kth Largest Element in a Stream

解法一 - Min Heap

這題應該算是非常直接,我們可以看 code:

class KthLargest {
public:
    KthLargest(int k, vector<int>& nums) {
        K = k;

        for(int i = 0; i < nums.size(); ++i) {
            minHeap.push(nums[i]);
            if(minHeap.size() > K) {
                minHeap.pop();
            }
        }
    }

    int add(int val) {
        minHeap.push(val);
        if(minHeap.size() > K) {
            minHeap.pop();
        }

        return minHeap.top();
    }

private:
    int K;
    priority_queue<int, vector<int>, greater<int>> minHeap; 
};

/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */

results matching ""

    No results matching ""