Skip to content

Latest commit

 

History

History
32 lines (26 loc) · 1.88 KB

풀이_LC914.md

File metadata and controls

32 lines (26 loc) · 1.88 KB

🧵 914. X of a Kind in a Deck of Cards

  • Date : 2022.02.20(일)
  • Time : 25분

Problem

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

Constraints

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

Example

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

풀이

    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        deckCounter = collections.Counter(deck).values()

        for i in range(2, max(deckCounter)+1):
            if all([not c % i for c in deckCounter]):
                return True
        return False

: 이 문제는 카드를 그룹으로 분할하려고 할 때 같은 갯수로 분할이 가능한 경우를 물어보고 있다. [1,1,1,2,2,2,3,3] 예시가 false 인 이유는 [1,1,1]은 한 그룹에 3개가 들어가는데, [3,3]은 2개가 들어가게 나눌 수 밖에 없기 때문이다. 그렇다고 [1,1], [1]도 1개가 들어가기 때문에 안된다. 문제를 풀이 위해서 collections 모듈을 사용했다. Count는 각 갯수를 세어주는 역할을 한다. 이제 거기서 몇개인지 values()만 가져왔다. 이제 같은 숫자로 계속 나눠떨어져야 한다. all() 함수는 iterable 내의 모든 요소가 참이거나 혹은 iterable 이 비어 있다면 True 를 반환하고, 그 외의 경우에는 False 를 반환하는 함수이다. 그래서 하나라도 나눠떨어지지 않으면 False를 return 해준다. 여기서 [1,1,2,2,3,3,3,3] 도 2,2,4개로 다른데 왜 이게 true이지? 궁금할 수 있다. 하지만 3,3,3,3은 [3,3], [3,3]으로 한번 더 쪼갤 수 있기 때문에 가능하다.