In a deck of cards, each card has an integer written on it.html
Return true
if and only if you can choose X >= 2
such that it is possible to split the entire deck into 1 or more groups of cards, where:git
X
cards.Example 1:github
Input: [1,2,3,4,4,3,2,1] Output: true Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
Example 2:less
Input: [1,1,1,2,2,2,3,3] Output: false Explanation: No possible partition.
Example 3:函数
Input: [1] Output: false Explanation: No possible partition.
Example 4:code
Input: [1,1] Output: true Explanation: Possible partition [1,1]
Example 5:htm
Input: [1,1,2,2,2,2] Output: true Explanation: Possible partition [1,1],[2,2],[2,2]
Note:blog
1 <= deck.length <= 10000
0 <= deck[i] < 10000
这道题给了一堆牌,问咱们能不能将这副牌分红若干堆,每堆均有X个,且每堆的牌数字都相同(这里不考虑花色)。既然要将相同的牌归类,确定要统计每种牌出现的个数,因此使用一个 HashMap 来创建牌跟其出现次数之间的映射。因为每堆X个,则若果某张牌的个数小于X,则确定没法分,因此X的范围是能够肯定的,为 [2, mn],其中 mn 是数量最少的牌的个数。遍历一遍 HashMap,找出最小的映射值 mn,若 mn 小于2,能够直接返回 false。不然就从2遍历到 mn,依次来检验候选值X。检验的方法是看其余每种牌的个数是否能整除候选值X,不必定非要相等,好比 [1, 1, 2, 2, 2, 2], K=2 时就能够分为三堆 [1, 1], [2, 2], [2, 2],即相同的牌也能够分到其余堆里,因此只要每种牌的个数能整除X便可,一旦有牌数不能整除X了,则当前X必定不行,还得继续检验下一个X值;若全部牌数都能整除X,能够返回 true。循环结束后返回 false,参见代码以下:leetcode
解法一:get
class Solution { public: bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int, int> cardCnt; for (int card : deck) ++cardCnt[card]; int mn = INT_MAX; for (auto &a : cardCnt) mn = min(mn, a.second); if (mn < 2) return false; for (int i = 2; i <= mn; ++i) { bool success = true; for (auto &a : cardCnt) { if (a.second % i != 0) { success = false; break; } } if (success) return true; } return false; } };
上面的解法是博主本身的解法,论坛上好多人使用了一个基于最大公约数 Greatest Common Divisor 的解法,写起来很简洁,但须要记住最大公约函数的写法,或者直接使用内置的 gcd 函数(感受有点耍赖哈~)。其实原理都差很少,这里是找每种牌数之间的最大公约数,只要这个 gcd 是大于1的,就表示能够找到符合题意的X,参见代码以下:
解法二:
class Solution { public: bool hasGroupsSizeX(vector<int>& deck) { unordered_map<int, int> cardCnt; for (int card : deck) ++cardCnt[card]; int res = 0; for (auto &a : cardCnt) { res = gcd(a.second, res); } return res > 1; } int gcd(int a, int b) { return a == 0 ? b : gcd(b % a, a); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/914
参考资料:
https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards/