LeetCode | 0914. X of a Kind in a Deck of Cards卡牌分組【Python】

LeetCode 0914. X of a Kind in a Deck of Cards卡牌分組【Easy】【Python】【數學】

Problem

LeetCode

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: 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.

Example 3:

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

Example 4:

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

Example 5:

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

Constraints:

  • 1 <= deck.length <= 10^4
  • 0 <= deck[i] < 10^4

問題

力扣

給定一副牌,每張牌上都寫着一個整數。

此時,你需要選定一個數字 X,使我們可以將整副牌按下述規則分成 1 組或更多組:

  • 每組都有 X 張牌。
  • 組內所有的牌上都寫着相同的整數。

僅當你可選的 X >= 2 時返回 true。

示例 1:

輸入:[1,2,3,4,4,3,2,1]
輸出:true
解釋:可行的分組是 [1,1],[2,2],[3,3],[4,4]

示例 2:

輸入:[1,1,1,2,2,2,3,3]
輸出:false
解釋:沒有滿足要求的分組。

示例 3:

輸入:[1]
輸出:false
解釋:沒有滿足要求的分組。

示例 4:

輸入:[1,1]
輸出:true
解釋:可行的分組是 [1,1]

示例 5:

輸入:[1,1,2,2,2,2]
輸出:true
解釋:可行的分組是 [1,1],[2,2],[2,2]

提示:

  • 1 <= deck.length <= 10^4
  • 0 <= deck[i] < 10^4

思路

數學

直接調用 Python 的 collections 庫,Counter 統計。
然後計算所有整數出現次數的最大公約數。
Python3代碼
from typing import List
import collections
import math

class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        # Counter統計出來是一個字典
        c = list(collections.Counter(deck).values())
        res = c[0]
        # 求所有數的最大公約數
        for x in c:
            res = math.gcd(res, x)
        return res > 1

GitHub鏈接

Python

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章