| | | 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 KthLargestElementInStreamSortedList : IKthLargestElementInStream |
| | | 16 | | { |
| | | 17 | | private readonly int _k; |
| | | 18 | | private readonly List<int> _nums; |
| | | 19 | | |
| | 2 | 20 | | public KthLargestElementInStreamSortedList(int k, int[] nums) |
| | 2 | 21 | | { |
| | 2 | 22 | | _k = k; |
| | 2 | 23 | | _nums = [.. nums.OrderDescending()]; |
| | 2 | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <summary> |
| | | 27 | | /// Time complexity - O(n) |
| | | 28 | | /// Space complexity - O(n + m) |
| | | 29 | | /// </summary> |
| | | 30 | | /// <param name="val"></param> |
| | | 31 | | /// <returns></returns> |
| | | 32 | | public int Add(int val) |
| | 9 | 33 | | { |
| | 9 | 34 | | Insert(val); |
| | | 35 | | |
| | 9 | 36 | | return _nums.ElementAt(_k - 1); |
| | 9 | 37 | | } |
| | | 38 | | |
| | | 39 | | private void Insert(int val) |
| | 9 | 40 | | { |
| | 54 | 41 | | for (var i = 0; i < _nums.Count; i++) |
| | 26 | 42 | | { |
| | 26 | 43 | | var sortedNum = _nums[i]; |
| | | 44 | | |
| | 26 | 45 | | if (sortedNum > val) |
| | 18 | 46 | | { |
| | 18 | 47 | | continue; |
| | | 48 | | } |
| | | 49 | | |
| | 8 | 50 | | _nums.Insert(i, val); |
| | | 51 | | |
| | 8 | 52 | | return; |
| | | 53 | | } |
| | | 54 | | |
| | 1 | 55 | | _nums.Add(val); |
| | 9 | 56 | | } |
| | | 57 | | } |