题目描述:
Alice has a hand of cards, given as an array of integers.
Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards.
Return true if and only if she can.
Example 1:
Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.
Note:
1. 1 <= hand.length <= 10000
2. 0 <= hand[i] <= 10^9
3. 1 <= W <= hand.length
用map记录每个数出现的次数,采用map的原因是map按照key从小到大排序,那么map.begin()对应最小的数字,我们就从最小的数字开始从map中删除,如果能全部删除说明可行。
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int W) {
int n=hand.size();
if(n%W!=0) return false;
map<int,int> m;
for(int i=0;i<hand.size();i++)
{
if(m.count(hand[i])==0) m[hand[i]]=1;
else m[hand[i]]++;
}
while(!m.empty())
{
int x=m.begin()->first;
for(int i=x;i<x+W;i++)
{
if(m.count(i)==0) return false;
else
{
m[i]--;
if(m[i]==0) m.erase(i);
}
}
}
return true;
}
};
本文介绍了一种手牌分组算法,旨在将一组整数卡片重新排列为大小相等且连续的子组。通过使用map记录每个数出现的次数,并从最小的数字开始删除,判断是否可以将手牌完美分组。
90

被折叠的 条评论
为什么被折叠?



