解题思路:
首先hand的大小一定 是groupSize的倍数,接着统计每个牌数,用map存储,再对hand进行排序,从头对每张牌进行访问,每次访问连续的groupSize,如果有缺失返回false,访问过后要将map中的记录-1,如果一张牌已经访问完,则从map中删除。代码如下:
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize) {
int len = hand.size();
if(len % groupSize != 0) {
return false;
}
sort(hand.begin(), hand.end());
unordered_map<int, int> mp;
for(auto& h : hand) {
mp[h] ++;
}
for(auto& h : hand) {
// 已经访问过了
if(!mp.count(h)) {
continue;
}
for(int i = 0; i < groupSize; i ++) {
int num = h + i;
if(!mp.count(num)) {
return false;
}
mp[num] --;
if(mp[num] == 0) {
mp.erase(num);
}
}
}
return true;
}
};