| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 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 class KthLargestElementInStreamSortedArray : IKthLargestElementInStream |
| | 16 | | { |
| | 17 | | private readonly int _k; |
| | 18 | | private readonly int[] _nums; |
| | 19 | |
|
| 2 | 20 | | public KthLargestElementInStreamSortedArray(int k, int[] nums) |
| 2 | 21 | | { |
| 2 | 22 | | _k = k; |
| | 23 | |
|
| 2 | 24 | | var newNums = new int[k]; |
| | 25 | |
|
| 2 | 26 | | Array.Fill(newNums, int.MinValue); |
| | 27 | |
|
| 2 | 28 | | if (nums.Length > 0) |
| 2 | 29 | | { |
| 14 | 30 | | Array.Sort(nums, (a, b) => b.CompareTo(a)); |
| | 31 | |
|
| 2 | 32 | | var i = 0; |
| | 33 | |
|
| 9 | 34 | | while (i < nums.Length && i < k) |
| 7 | 35 | | { |
| 7 | 36 | | newNums[i] = nums[i]; |
| | 37 | |
|
| 7 | 38 | | i++; |
| 7 | 39 | | } |
| 2 | 40 | | } |
| | 41 | |
|
| 2 | 42 | | _nums = newNums; |
| 2 | 43 | | } |
| | 44 | |
|
| | 45 | | /// <summary> |
| | 46 | | /// Time complexity - O(k) |
| | 47 | | /// Space complexity - O(k) |
| | 48 | | /// </summary> |
| | 49 | | /// <param name="val"></param> |
| | 50 | | /// <returns></returns> |
| | 51 | | public int Add(int val) |
| 9 | 52 | | { |
| 80 | 53 | | for (var i = 0; i < _nums.Length; i++) |
| 31 | 54 | | { |
| 31 | 55 | | if (_nums[i] < val) |
| 11 | 56 | | { |
| 11 | 57 | | (_nums[i], val) = (val, _nums[i]); |
| 11 | 58 | | } |
| 31 | 59 | | } |
| | 60 | |
|
| 9 | 61 | | return _nums[_k - 1]; |
| 9 | 62 | | } |
| | 63 | | } |