|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | +import java.util.PriorityQueue; |
| 7 | + |
| 8 | +/** |
| 9 | + * 703. Kth Largest Element in a Stream |
| 10 | + * |
| 11 | + * 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. |
| 12 | + * Your KthLargest class will have a constructor which accepts an integer K and an integer array nums, |
| 13 | + * which contains initial elements from the stream. |
| 14 | + * For each call to the method KthLargest.add, return the element representing the kth largest element in the stream. |
| 15 | + * |
| 16 | + * Example: |
| 17 | + * |
| 18 | + * int K = 3; |
| 19 | + * int[] arr = [4,5,8,2]; |
| 20 | + * KthLargest kthLargest = new KthLargest(3, arr); |
| 21 | + * kthLargest.add(3); // returns 4 |
| 22 | + * kthLargest.add(5); // returns 5 |
| 23 | + * kthLargest.add(10); // returns 5 |
| 24 | + * kthLargest.add(9); // returns 8 |
| 25 | + * kthLargest.add(4); // returns 8 |
| 26 | + * Note: |
| 27 | + * You may assume that nums' length ≥ K-1 and K ≥ 1. |
| 28 | + */ |
| 29 | +public class _703 { |
| 30 | + public static class Solution1 { |
| 31 | + public static class KthLargest { |
| 32 | + PriorityQueue<Integer> heap; |
| 33 | + int K; |
| 34 | + public KthLargest(int k, int[] nums) { |
| 35 | + heap = new PriorityQueue<>(Collections.reverseOrder()); |
| 36 | + for (int num : nums) { |
| 37 | + heap.offer(num); |
| 38 | + } |
| 39 | + K = k; |
| 40 | + } |
| 41 | + |
| 42 | + public int add(int val) { |
| 43 | + List<Integer> tmp = new ArrayList<>(); |
| 44 | + int result = 0; |
| 45 | + int tmpK = K; |
| 46 | + heap.offer(val); |
| 47 | + while (tmpK-- > 0) { |
| 48 | + result = heap.poll(); |
| 49 | + tmp.add(result); |
| 50 | + } |
| 51 | + for (int num : tmp) { |
| 52 | + heap.offer(num); |
| 53 | + } |
| 54 | + return result; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
0 commit comments