1??普通库函数排序:
class Solution { public int findKthLargest(int[] nums, int k) { Arrays.sort(nums); return nums[nums.length-k]; } }
2??堆排序:
时间复杂度 O(nlogk),空间复杂度 O(k)
三种函数poll,peek,element,add
共同点:
不同点:
Java 使用 PriorityQueue<>((x, y) -> (y - x))
可方便实现大顶堆。
Java 使用 PriorityQueue<>()
可方便实现小顶堆。
实际上小顶堆内部默认的完整格式是:PriorityQueue<>(
(x, y) -> (x - y)
),尤其注意全部参数的设置都是括号里面的写法;
class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> q=new PriorityQueue<>(); for(int n:nums){ q.add(n); if(q.size()>k){ q.poll(); } } return q.peek(); } }
原文:https://www.cnblogs.com/sjh-dora/p/12898701.html