The K-th largest element in the LeetCode703 data stream
Design a class to find the K-th largest element in the data flow. Note that it is the K-th largest element after sorting, not the K-th different element.
Your KthLargest class needs a constructor that receives both the integer K and the integer array nums. It contains the initial elements in the data stream. Each time khtlargest.add is called, the K-th largest element in the current data flow is returned.
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
Explain:
You can assume that the length of nums is ≥ k-1 and K ≥ 1.
Solution 1: maintain a list of length K. Time complexity: O(N*K*log2K)
class KthLargest { private List<Integer> list; private int index; public KthLargest(int k, int[] nums) { list = new ArrayList<Integer>(k); index = k; Arrays.sort(nums); int i = 0; for (; i < k && i < nums.length; i++) { list.add(nums[nums.length - 1 - i]); } while (i++ < k) { list.add(Integer.MIN_VALUE); } //Sort the array, keeping the list.get(0) position as the K-th largest element Collections.sort(list); } public int add(int val) { //If the size of the newly inserted value is less than the K-th element, the K-th element will be returned. if (val < list.get(0)) { return list.get(0); } else { //If the size of the new inserted value is not less than the K-th element, move out the K-th element and insert the new value. list.remove(0); list.add((Integer)val); } //Sort the array, keeping the list.get(0) position as the K-th largest element Collections.sort(list); return list.get(0); } }
Solution 2: maintain a small top heap with the size of K (you can use Java priority queue). If the insertion value is less than the top element of the heap, the heap will not be operated. If the insertion value is greater than the heap top element, move the heap top element out and insert a new element. Time complexity: O(N*Log2K)
class KthLargest { private final PriorityQueue<Integer> minHeap; final int index; public KthLargest(int k, int[] nums) { this.k = k; minHeap = new PriorityQueue<Integer>(k); for (int i = 0; i < nums.lengthl; i++) { add(nums[i]); } } public int add(int val) { if (minHeap.size() < k) { minHeap.offer(val); } else if (minHeap.peek() < val) { minHeap.poll(); minHeap.offer(val); } return minHeap.peek(); } }