mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
java: add «846. Hand of Straights»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
26e9547b32
commit
5c968ef149
1 changed files with 34 additions and 0 deletions
34
java/hand-of-straights.java
Normal file
34
java/hand-of-straights.java
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue