使用堆,堆插入一个数据是logk,删除一个数据是logk,复杂度为logk
Java
class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueueminQueue = 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 & nums, int k) { priority_queue