1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-09-16 16:36:56 +02:00
LeetCode/java/hand-of-straights.java
Matej Focko 5c968ef149
java: add «846. Hand of Straights»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-06-06 11:38:33 +02:00

34 lines
807 B
Java

import java.util.TreeMap;
class Solution {
public boolean isNStraightHand(int[] hand, int groupSize) {
if (hand.length % groupSize != 0) {
return false;
}
TreeMap<Integer, Integer> cards = new TreeMap<>();
for (int card : hand) {
cards.compute(card, (c, present) -> 1 + ((present == null) ? 0 : present));
}
while (!cards.isEmpty()) {
int card = cards.entrySet().iterator().next().getKey();
for (int i = 0; i < groupSize; ++i) {
// card doesn't exist
if (!cards.containsKey(card + i)) {
return false;
}
cards.put(card + i, cards.get(card + i) - 1);
// remove entry of used cards
if (cards.get(card + i) == 0) {
cards.remove(card + i);
}
}
}
return true;
}
}