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(); } };
使用快速選擇,就是用快排改的,將數組分組,但是這個也是一個不穩定的做法