leetcode 703. Kth Largest Element in a Stream & c++ priority_queue & minHeap/maxHeap

703. Kth Largest Element in a Stream & c++ priority_queue & minHeap/maxHeap

相关链接

leetcode
c++ priority_queue cplusplus
c++ priority_queue cnblog

背景知识

  堆是算法中常用的数据结构之一,其结构是完全二叉树,但实现的方法最常见的是使用数组;这里主要介绍小顶堆,其根元素最小,对于任何一个节点来说,他都比其后代要小;访问器根元素的时间为O(1);树的高度严格控制在 log(n) 以内,故每次插入元素的时间为 O(log(n)).

  在c++的STL中提供了现成的堆模板给我们使用;你需要引入头文件queue.h即可;
具体使用如下

#include<queue.h>

using namespace std;

int main()
{
    //大顶堆
    priority_queue<int> maxHeap;
    //等价于
    priority_queue<int, vector<int>, less<int> > maxHeap1;

    //小顶堆
    priority_queue<int, vector<int>, greater<int> > maxHeap1;

}

描述

   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.

solution1

  用一个小顶堆保存最大的K个数字;根节点处为K个数字中最小的一个,也是所有数据中第k大的数字;每当有新元素进来的时候,拿走小顶堆中最小的元素;


using namespace std;

class KthLargest {
public:
	int k;
	priority_queue<int, vector<int>, greater<int> > minHeap;
public:
	KthLargest(int k, vector<int>& nums) :minHeap(nums.begin(), nums.end()) {
		this->k = k;
	}

	int add(int val) {
		minHeap.push(val);
		while (k < minHeap.size())
			minHeap.pop();
		return minHeap.top();
	}
};



int main()
{
	priority_queue<int> maxHeap;
	//priority_queue<int, vector<int>, less<int> > maxHeap;
	priority_queue<int, vector<int>, greater<int> > minHeap;

	int k = 3;
	vector<int> arr = { 4,5,8,2 };
	
	KthLargest kthLargest =KthLargest(3, arr);
	cout<<kthLargest.add(3);   // returns 4
	cout << kthLargest.add(5);   // returns 5
	cout << kthLargest.add(10);  // returns 5
	cout << kthLargest.add(9);   // returns 8
	cout << kthLargest.add(4);   // returns 8

	system("pause");
}
上一篇:CSS 盒模型


下一篇:Sublime 自动根据窗口宽度换行 / 更改默认 Word Wrap Width