| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.KthLargestElementInStream; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class KthLargestElementInStreamPriorityQueue : IKthLargestElementInStream |
| | | 16 | | { |
| | | 17 | | private readonly int _k; |
| | 2 | 18 | | private readonly PriorityQueue<int, int> _priorityQueue = new(); |
| | | 19 | | |
| | 2 | 20 | | public KthLargestElementInStreamPriorityQueue(int k, int[] nums) |
| | 2 | 21 | | { |
| | 2 | 22 | | _k = k; |
| | | 23 | | |
| | 26 | 24 | | foreach (var num in nums) |
| | 10 | 25 | | { |
| | 10 | 26 | | Add(num); |
| | 10 | 27 | | } |
| | 2 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Time complexity - O(log k) |
| | | 32 | | /// Space complexity - O(k) |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="val"></param> |
| | | 35 | | /// <returns></returns> |
| | | 36 | | public int Add(int val) |
| | 19 | 37 | | { |
| | 19 | 38 | | if (_priorityQueue.Count < _k) |
| | 7 | 39 | | { |
| | 7 | 40 | | _priorityQueue.Enqueue(val, val); |
| | 7 | 41 | | } |
| | 12 | 42 | | else if (val > _priorityQueue.Peek()) |
| | 7 | 43 | | { |
| | 7 | 44 | | _priorityQueue.Dequeue(); |
| | 7 | 45 | | _priorityQueue.Enqueue(val, val); |
| | 7 | 46 | | } |
| | | 47 | | |
| | 19 | 48 | | return _priorityQueue.Peek(); |
| | 19 | 49 | | } |
| | | 50 | | } |