Question:

In a deck of cards, each card has an integer written on it.

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:

  • Each group has exactly X cards.

  • All the cards in each group have the same integer.

Example:

  1. Input: [1,2,3,4,4,3,2,1]
  2. Output: true
  3. Explanation: Possible partition [1,1],[2,2],[3,3],[4,4]
  4. Input: [1]
  5. Output: false
  6. Explanation: No possible partition.
  7. Input: [1,1]
  8. Output: true
  9. Explanation: Possible partition [1,1]
  1. Input: [1,1,1,2,2,2,3,3]
  2. Output: false
  3. Explanation: No possible partition.
  4. Input: [1,1,2,2,2,2]
  5. Output: true
  6. Explanation: Possible partition [1,1],[2,2],[2,2]

Solution:

  1. /**
  2. * @param {number[]} deck
  3. * @return {boolean}
  4. */
  5. var hasGroupsSizeX = function(deck) {
  6. // 先归类
  7. let map = {};
  8. for (let i=0; i<deck.length; i++) {
  9. if (!map[deck[i]]) {
  10. map[deck[i]] = 0
  11. }
  12. map[deck[i]]++;
  13. }
  14. // 找最小长度
  15. let minLen;
  16. for (let j in map) {
  17. if (!minLen) {
  18. minLen = map[j]
  19. }else{
  20. minLen = Math.min(minLen,map[j])
  21. }
  22. }
  23. // 判断最小长度是否大于等于2
  24. if (minLen<2) return false;
  25. var getMgn = function (a,b) {
  26. if (a % b === 0) {
  27. return b
  28. }
  29. return arguments.callee(b, a % b);
  30. }
  31. for (let k in map) {
  32. // 求公约数
  33. let mgn = getMgn(map[k],minLen);
  34. console.log(mgn,k,minLen,map[k])
  35. if (mgn === 1) {
  36. return false
  37. }
  38. }
  39. return true
  40. };

Runtime: 60 ms, faster than 100.00% of JavaScript online submissions for X of a Kind in a Deck of Cards.