返回介绍

solution / 0900-0999 / 0914.X of a Kind in a Deck of Cards / README_EN

发布于 2024-06-17 01:03:33 字数 2973 浏览 0 评论 0 收藏 0

914. X of a Kind in a Deck of Cards

中文文档

Description

You are given an integer array deck where deck[i] represents the number written on the ith card.

Partition the cards into one or more groups such that:

  • Each group has exactly x cards where x > 1, and
  • All the cards in one group have the same integer written on them.

Return true_ if such partition is possible, or _false_ otherwise_.

 

Example 1:

Input: deck = [1,2,3,4,4,3,2,1]
Output: true
Explanation: Possible partition [1,1],[2,2],[3,3],[4,4].

Example 2:

Input: deck = [1,1,1,2,2,2,3,3]
Output: false
Explanation: No possible partition.

 

Constraints:

  • 1 <= deck.length <= 104
  • 0 <= deck[i] < 104

Solutions

Solution 1

class Solution:
  def hasGroupsSizeX(self, deck: List[int]) -> bool:
    vals = Counter(deck).values()
    return reduce(gcd, vals) >= 2
class Solution {
  public boolean hasGroupsSizeX(int[] deck) {
    int[] cnt = new int[10000];
    for (int v : deck) {
      ++cnt[v];
    }
    int g = -1;
    for (int v : cnt) {
      if (v > 0) {
        g = g == -1 ? v : gcd(g, v);
      }
    }
    return g >= 2;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
class Solution {
public:
  bool hasGroupsSizeX(vector<int>& deck) {
    int cnt[10000] = {0};
    for (int& v : deck) ++cnt[v];
    int g = -1;
    for (int& v : cnt) {
      if (v) {
        g = g == -1 ? v : __gcd(g, v);
      }
    }
    return g >= 2;
  }
};
func hasGroupsSizeX(deck []int) bool {
  cnt := make([]int, 10000)
  for _, v := range deck {
    cnt[v]++
  }
  g := -1
  for _, v := range cnt {
    if v > 0 {
      if g == -1 {
        g = v
      } else {
        g = gcd(g, v)
      }
    }
  }
  return g >= 2
}

func gcd(a, b int) int {
  if b == 0 {
    return a
  }
  return gcd(b, a%b)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文