How to Compute Kth Largest Element in a Stream?

  • 时间:2020-09-28 16:28:51
  • 分类:网络文摘
  • 阅读:92 次

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream.

Example:
int k = 3;
int[] arr = [4,5,8,2];
KthLargest kthLargest = new KthLargest(3, arr);
kthLargest.add(3); // returns 4
kthLargest.add(5); // returns 5
kthLargest.add(10); // returns 5
kthLargest.add(9); // returns 8
kthLargest.add(4); // returns 8
Note:
You may assume that nums’ length ≥ k-1 and k ≥ 1.

Compute the K-th Largest using Priority Queue

In the constructor, we store the K and construct a priority queue. Then we need to push the elements into the priority queue.

When we add another element to the priority queue, we need to pop extra elements until we have exactly K elements internally in the priority queue.

Adding one element to the priority queue takes O(logN) time complexity.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class KthLargest {
public:
    KthLargest(int k, vector<int>& nums) {
       this->kth = k;
       for (const auto &n: nums) {
           pq.push(n);
       } 
    }
    
    int add(int val) {
       pq.push(val);
       while (kth < pq.size()) {
           pq.pop();
       }
       return pq.top();
    }
private:
    int kth;
    priority_queue<int, vector<int>, std::greater<int>> pq;
};
 
/**
 * Your KthLargest object will be instantiated and called as such:
 * KthLargest* obj = new KthLargest(k, nums);
 * int param_1 = obj->add(val);
 */
class KthLargest {
public:
    KthLargest(int k, vector<int>& nums) {
       this->kth = k;
       for (const auto &n: nums) {
           pq.push(n);
       } 
    }
    
    int add(int val) {
       pq.push(val);
       while (kth < pq.size()) {
           pq.pop();
       }
       return pq.top();
    }
private:
    int kth;
    priority_queue<int, vector<int>, std::greater<int>> pq;
};

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

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
中文视听网手机版中文视听APP(最新版)下载  作文写作指导:小学生作文该怎么写?  小学作文需增长孩子的视野,鼓励孩子表达  六年级劳动节作文  五年级作文:不该丢失的童年色彩  六年级作文:我和秋天有个约会  数学故事:流传久远的算术趣题  趣味数学:什么是完全数  数学小故事:高斯巧解算术题  数学趣味故事:测量金字塔的高度 
评论列表
添加评论