LeetCode[215] Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

For example,
Given [3,2,1,5,6,4] and k = 2, return 5.

Note: 
You may assume k is always valid, 1 ≤ k ≤ array's length.


用priority_queue,定義小端隊列,priority_queue<int, vector<int>, greater<int>>,小的元素先出列,隊頭爲最小元素,也即第K大元素

遍歷nums數組,當隊列大小爲k的時候如果i>topK.top(),隊列彈出隊頭,把i放進去,否則跳過元素i

class Solution {
public:
	int findKthLargest(vector<int>& nums, int k) {
		priority_queue<int, vector<int>, greater<int>> topK;
		for (auto i : nums)
		{
			if (topK.size() == k)
			{
				if (topK.top() >= i)
					continue;
				topK.pop();
			}
			topK.push(i);
		}
		return topK.top();
	}
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章