爱丽丝有一手(hand
)由整数数组给定的牌。
现在她想把牌重新排列成组,使得每个组的大小都是 W
,且由 W
张连续的牌组成。
如果她可以完成分组就返回 true
,否则返回 false
。
示例 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
C++
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W)
{
int n=hand.size();
if(0!=n%W)
{
return false;
}
if(1==W)
{
return true;
}
sort(hand.begin(),hand.end());
map<int,int> tmp;
for(int i=0;i<n;i++)
{
tmp[hand[i]]++;
}
map<int,int>::iterator it;
for(it=tmp.begin();it!=tmp.end();it++)
{
int count=it->second;
if(count>0)
{
for(int i=0;i<W;i++)
{
tmp[it->first+i]-=count;
if(tmp[it->first+i]<0)
{
return false;
}
}
}
}
return true;
}
};
python
class Solution:
def isNStraightHand(self, hand, W):
"""
:type hand: List[int]
:type W: int
:rtype: bool
"""
n=len(hand)
if n%W!=0:
return False
hand.sort()
tmp=collections.Counter(hand)
for key in tmp:
if tmp[key]>0:
count=tmp[key]
for i in range(W):
tmp[key+i]-=count
if tmp[key+i]<0:
return False
return True