- 一手顺子
爱丽丝有一手(hand)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W,且由 W 张连续的牌组成。
如果她可以完成分组就返回 true,否则返回 false。
注意:此题目与 1296 重复:https://leetcode-cn.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
示例 1:
输入:hand = [1,2,3,6,2,3,4,7,8], W = 3
输出:true
解释:爱丽丝的手牌可以被重新排列为 [1,2,3],[2,3,4],[6,7,8]。
示例 2:
输入:hand = [1,2,3,4,5], W = 4
输出:false
解释:爱丽丝的手牌无法被重新排列成几个大小为 4 的组。
提示:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length
题解
排序然后利用map统计数目即可,比较简单。
AC代码
class Solution {
public:
map<int,int>count;
bool isNStraightHand(vector<int>& hand, int groupSize)
{
if(hand.size()%groupSize!=0)return false;
sort(hand.begin(),hand.end());
count.clear();
for(int i=0;i<hand.size();i++)
{
count[hand[i]]++;
}
for(int i=0;i<hand.size();i++)
{
if(count[hand[i]]>0)
{
for(int j=hand[i];j<hand[i]+groupSize;j++)
{
if(count[j]>0)
{
count[j]--;
}
else return false;//没法构成连续
}
}
}
return true;
}
};