题目地址
思路
首先阅读题干,发现hand数组并不是有序数组,所以我们可以用sort()函数将其按照升序排序;
然后本题的目标是判断是否可以合理按组分牌;
所以首先第一个判定就是求模:即hand.size()%groupsize==0
,如果不等于0,那么一定是不能分牌,返回false
;
然后我们可以使用贪心的思想,即对于hand
数组中的每一个元素num
(排序过后的数组),他处于group
数组的第0位,所以group
数组值的范围为[num,num+groupsize-1]
,即可以对于每一个num,搜索hand数组中是否还存在比他大一的数字。如果不存在就返回false;
详细的解题过程请看下面的代码,代码写的比较清楚。
代码实现(C++)
class Solution {
public:
bool isNStraightHand(vector<int>& hand, int groupSize)
{
if(hand.size()%groupSize!=0)
{
return false;
}
sort(hand.begin(),hand.end());
unordered_map<int,int> map;
//int cl=hand.size()/groupSize;
//vector<int,int> ans(cl,vector<int>(groupSize));
for(int i=0;i<hand.size();i++)
{
map[hand[i]]++;
}
for(auto &num : hand)
{
if(!map[num])
{
continue;
}
for(int j=0;j<groupSize;j++)
{
int res=num+j;
if(!map[res])
{
return false;
}
map[res]--;
if(!map[res])
{
map.erase(res);
}
}
}
return true;
}
};
总结
这道题是典型的贪心思想和map的结合使用。