用map解决爱丽丝的手牌
题目如下
解题思路如下
1、判断数组元素的个数能不能被W整除
2、
记录数组中的相同数据的个数。使用一次减1。
然后即可判断三个数据是否连续。
这样我们就知道数据出现了几次。
程序遍历草图如下
解题代码如下
#include<iostream>
#include<map>
#include<vector>
using namespace std;
bool IsNStraightHand(vector<int>& hand, int w)
{
if (hand.size() < w) return false;
if (hand.size() % w != 0) return false;
map<int, int> iimap;
for (auto num : hand)
{
++iimap[num];
}
for (auto it = iimap.begin(); it != iimap.end(); ++it)
{
if (it->second > 0)
{
for (int i = 1; i < w; ++i)
{
int next = it->first + i;
if (iimap.find(next) != iimap.end() && iimap[next] >= it->second)
{
iimap[next] -= it->second;
}
else
{
return false;
}
}
}
}
return true;
}
int main()
{
vector<int>hand = { 1,2,3,6,2,3,4,7,8 };
cout << IsNStraightHand(hand, 3) << endl;
return 0;
}