https://leetcode.com/problems/kth-largest-element-in-an-array/
使用堆,堆插入一个数据是logk,删除一个数据是logk,复杂度为logk
Java
class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> minQueue = new PriorityQueue<>(k); for (int num : nums) { if (minQueue.size() < k || num > minQueue.peek()) minQueue.offer(num); if (minQueue.size() > k) minQueue.poll(); } return minQueue.peek(); } }
C++的
class Solution { public: int findKthLargest(vector<int>& nums, int k) { priority_queue<int, vector<int>, greater<int> >pq; for(auto num:nums) { if(pq.size()<k) pq.push(num); else if(num>pq.top()) pq.pop(),pq.push(num); } return pq.top(); } };
使用快速选择,就是用快排改的,将数组分组,但是这个也是一个不稳定的做法