| | 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.DivideArrayInSetsOfKConsecutiveNumbers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class DivideArrayInSetsOfKConsecutiveNumbersSortedDictionary : IDivideArrayInSetsOfKConsecutiveNumbers |
| | 16 | | { |
| | 17 | | public bool IsPossibleDivide(int[] nums, int k) |
| 15 | 18 | | { |
| 15 | 19 | | if (nums.Length % k != 0) |
| 3 | 20 | | { |
| 3 | 21 | | return false; |
| | 22 | | } |
| | 23 | |
|
| 12 | 24 | | var numsDictionary = new SortedDictionary<int, int>(); |
| | 25 | |
|
| 168 | 26 | | foreach (var num in nums) |
| 66 | 27 | | { |
| 66 | 28 | | if (!numsDictionary.TryAdd(num, 1)) |
| 10 | 29 | | { |
| 10 | 30 | | numsDictionary[num]++; |
| 10 | 31 | | } |
| 66 | 32 | | } |
| | 33 | |
|
| 33 | 34 | | while (numsDictionary.Count > 0) |
| 23 | 35 | | { |
| 23 | 36 | | var firstNum = numsDictionary.First().Key; |
| | 37 | |
|
| 168 | 38 | | for (var i = 0; i < k; i++) |
| 63 | 39 | | { |
| 63 | 40 | | var currentNum = firstNum + i; |
| | 41 | |
|
| 63 | 42 | | if (numsDictionary.TryGetValue(currentNum, out var value)) |
| 61 | 43 | | { |
| 61 | 44 | | if (value == 1) |
| 53 | 45 | | { |
| 53 | 46 | | numsDictionary.Remove(currentNum); |
| 53 | 47 | | } |
| | 48 | | else |
| 8 | 49 | | { |
| 8 | 50 | | numsDictionary[currentNum] = value - 1; |
| 8 | 51 | | } |
| 61 | 52 | | } |
| | 53 | | else |
| 2 | 54 | | { |
| 2 | 55 | | return false; |
| | 56 | | } |
| 61 | 57 | | } |
| 21 | 58 | | } |
| | 59 | |
|
| 10 | 60 | | return true; |
| 15 | 61 | | } |
| | 62 | | } |