爱丽丝有一手(hand)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。
如果她可以完成分组就返回 true,否则返回 false。
注意:此题目与 1296 重复:https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/hand-of-straights
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.TreeMap;
class Solution {
public boolean isNStraightHand(int[] hand, int W) {
TreeMap<Integer, Integer> count = new TreeMap();
for (int card: hand) {
if (!count.containsKey(card))
count.put(card, 1);
else
count.replace(card, count.get(card) + 1);
}
while (count.size() > 0) {
int first = count.firstKey();
for (int card = first; card < first + W; ++card) {
if (!count.containsKey(card)) return false;
int c = count.get(card);
if (c == 1) count.remove(card);
else count.replace(card, c - 1);
}
}
return true;
}
}