mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-14 01:49:41 +01:00
35 lines
807 B
Java
35 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;
|
||
|
}
|
||
|
}
|