题目 846. 一手顺子
难度 中等
爱丽丝有一手(hand)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。
如果她可以完成分组就返回 true,否则返回 false。
思路
因为手中最小的牌也一定是某个分组中的起始牌,所以反复从手中最小的牌开始组建一个长度为 W 的组。
算法
使用 TreeMap 或 dict 记录每种牌的数量 {card: number of copies of card}。
然后反复执行以下步骤:找到最小的一张牌(假设是 x),然后试图将 x, x+1, x+2, …, x+W-1 这些牌的计数减 1。如果每次都能找到这样的组且最终手里无牌,那么分组成功,否则失败。
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;
}
}
作者:LeetCode
链接:https://leetcode-cn.com/problems/hand-of-straights/solution/yi-shou-shun-zi-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。