|
5 | 5 | import java.util.List;
|
6 | 6 | import java.util.PriorityQueue;
|
7 | 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 | 8 | public class _703 {
|
30 |
| - public static class Solution1 { |
31 |
| - public static class KthLargest { |
32 |
| - PriorityQueue<Integer> heap; |
33 |
| - int maxK; |
| 9 | + public static class Solution1 { |
| 10 | + public static class KthLargest { |
| 11 | + PriorityQueue<Integer> heap; |
| 12 | + int maxK; |
34 | 13 |
|
35 |
| - public KthLargest(int k, int[] nums) { |
36 |
| - heap = new PriorityQueue<>(Collections.reverseOrder()); |
37 |
| - for (int num : nums) { |
38 |
| - heap.offer(num); |
39 |
| - } |
40 |
| - maxK = k; |
41 |
| - } |
| 14 | + public KthLargest(int k, int[] nums) { |
| 15 | + heap = new PriorityQueue<>(Collections.reverseOrder()); |
| 16 | + for (int num : nums) { |
| 17 | + heap.offer(num); |
| 18 | + } |
| 19 | + maxK = k; |
| 20 | + } |
42 | 21 |
|
43 |
| - public int add(int val) { |
44 |
| - List<Integer> tmp = new ArrayList<>(); |
45 |
| - int result = 0; |
46 |
| - int tmpK = maxK; |
47 |
| - heap.offer(val); |
48 |
| - while (tmpK-- > 0) { |
49 |
| - result = heap.poll(); |
50 |
| - tmp.add(result); |
51 |
| - } |
52 |
| - for (int num : tmp) { |
53 |
| - heap.offer(num); |
| 22 | + public int add(int val) { |
| 23 | + List<Integer> tmp = new ArrayList<>(); |
| 24 | + int result = 0; |
| 25 | + int tmpK = maxK; |
| 26 | + heap.offer(val); |
| 27 | + while (tmpK-- > 0) { |
| 28 | + result = heap.poll(); |
| 29 | + tmp.add(result); |
| 30 | + } |
| 31 | + for (int num : tmp) { |
| 32 | + heap.offer(num); |
| 33 | + } |
| 34 | + return result; |
| 35 | + } |
54 | 36 | }
|
55 |
| - return result; |
56 |
| - } |
57 | 37 | }
|
58 |
| - } |
59 | 38 | }
|
0 commit comments