java: add «846. Hand of Straights»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-06-06 11:38:33 +02:00
parent 26e9547b32
commit 5c968ef149
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,34 @@
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;
}
}