153.Kth Largest Element in a Stream
题目:
Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.
设计一个类来查找流中第k个最大元素。 请注意,它是排序顺序中的第k个最大元素,而不是第k个不同元素。
Your KthLargest
class will have a constructor which accepts an integer k
and an integer array nums
, which contains initial elements from the stream. For each call to the method KthLargest.add
, return the element representing the kth largest element in the stream.
你的KthLargest类将有一个构造函数,它接受一个整数k和一个整数数组nums,它包含来自流的初始元素。 对于方法KthLargest.add的每次调用,返回表示流中第k个最大元素的元素。
Example:
int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8
Note:
You may assume that nums
' length ≥ k-1
and k
≥ 1.
您可以假设nums的长度≥k-1且k≥1。
解答:
方法一:优先级队列(自动排序的特性)
1 class KthLargest { 2 3 final PriorityQueue<Integer> q; 4 final int k; 5 6 public KthLargest(int k, int[] nums) { 7 this.k=k; 8 q=new PriorityQueue<>(k); 9 for(int n:nums) 10 add(n); 11 } 12 13 public int add(int val) { 14 if(q.size()<k) 15 q.offer(val); 16 else if(q.peek()<val){ 17 q.poll(); 18 q.offer(val); 19 } 20 return q.peek(); 21 } 22 } 23 24 /** 25 * Your KthLargest object will be instantiated and called as such: 26 * KthLargest obj = new KthLargest(k, nums); 27 * int param_1 = obj.add(val); 28 */
方法二:快速排序(从大到小)
详解: