| | | 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.HandOfStraights; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class HandOfStraightsDictionary : IHandOfStraights |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n log n) |
| | | 19 | | /// Space complexity - O(n) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="hand"></param> |
| | | 22 | | /// <param name="groupSize"></param> |
| | | 23 | | /// <returns></returns> |
| | | 24 | | public bool IsNStraightHand(int[] hand, int groupSize) |
| | 15 | 25 | | { |
| | 15 | 26 | | if (hand.Length % groupSize != 0) |
| | 3 | 27 | | { |
| | 3 | 28 | | return false; |
| | | 29 | | } |
| | | 30 | | |
| | 12 | 31 | | Array.Sort(hand); |
| | | 32 | | |
| | 12 | 33 | | var cardsDictionary = new Dictionary<int, int>(); |
| | | 34 | | |
| | 168 | 35 | | foreach (var card in hand) |
| | 66 | 36 | | { |
| | 66 | 37 | | if (!cardsDictionary.TryAdd(card, 1)) |
| | 10 | 38 | | { |
| | 10 | 39 | | cardsDictionary[card]++; |
| | 10 | 40 | | } |
| | 66 | 41 | | } |
| | | 42 | | |
| | 33 | 43 | | while (cardsDictionary.Count > 0) |
| | 23 | 44 | | { |
| | 23 | 45 | | var firstCard = cardsDictionary.First().Key; |
| | | 46 | | |
| | 168 | 47 | | for (var i = 0; i < groupSize; i++) |
| | 63 | 48 | | { |
| | 63 | 49 | | var currentCard = firstCard + i; |
| | | 50 | | |
| | 63 | 51 | | if (cardsDictionary.TryGetValue(currentCard, out var value)) |
| | 61 | 52 | | { |
| | 61 | 53 | | if (value == 1) |
| | 53 | 54 | | { |
| | 53 | 55 | | cardsDictionary.Remove(currentCard); |
| | 53 | 56 | | } |
| | | 57 | | else |
| | 8 | 58 | | { |
| | 8 | 59 | | cardsDictionary[currentCard] = value - 1; |
| | 8 | 60 | | } |
| | 61 | 61 | | } |
| | | 62 | | else |
| | 2 | 63 | | { |
| | 2 | 64 | | return false; |
| | | 65 | | } |
| | 61 | 66 | | } |
| | 21 | 67 | | } |
| | | 68 | | |
| | 10 | 69 | | return true; |
| | 15 | 70 | | } |
| | | 71 | | } |