forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0846-hand-of-straights.cs
45 lines (36 loc) · 1.16 KB
/
0846-hand-of-straights.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public class Solution
{
//Same problem as #1296. Divide Array in Sets of K Consecutive Numbers
//T: O(logN) for min heap, N is for all the items-> so overall O(NlogN)
public bool IsNStraightHand(int[] hand, int groupSize)
{
if (hand.Length % groupSize != 0)
return false;
var dictionary = new Dictionary<int, int>();
var minHeap = new PriorityQueue<int, int>();
foreach (var item in hand)
{
dictionary.TryAdd(item, 0);
dictionary[item]++;
}
// heapify is linear algorithm
foreach (var key in dictionary.Keys)
minHeap.Enqueue(key, key);
while (minHeap.Count > 0)
{
var first = minHeap.Peek();
for (var i = first; i < first + groupSize; i++)
{
if (!dictionary.ContainsKey(i))
return false;
dictionary[i]--;
if (dictionary[i] == 0)
if (i != minHeap.Peek())
return false;
else
minHeap.Dequeue();
}
}
return true;
}
}