LeetCode - Hand of Straights(846)

marafo·2021년 7월 24일
0

Sorting - Medium

Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size groupSize, and consists of groupSize consecutive cards.

Given an integer array hand where hand[i] is the value written on the ith card and an integer groupSize, return true if she can rearrange the cards, or false otherwise.

Example 1:

Input: hand = [1,2,3,6,2,3,4,7,8], groupSize = 3
Output: true
Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8]
Example 2:

Input: hand = [1,2,3,4,5], groupSize = 4
Output: false
Explanation: Alice's hand can not be rearranged into groups of 4.

Constraints:

∙ 1 <= hand.length <= 104
∙ 0 <= hand[i] <= 109
∙ 1 <= groupSize <= hand.length


실패

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        if groupSize == 1:
            return True
        
        # if groupSize >= len(hand):
        #     return T
        a = list(combinations([2, 1], 2))
        print(a)
        
        combi = list(combinations(hand, groupSize))
        print(combi)
        start = combi[0][0]
        c = 1
        
        for i in range(1, len(combi)):
            if combi[i][0] != start:
                start = combi[i][0]
                c += 1
            
            if c == groupSize:
                return True
            
        return False

힙 자료구조 내장함수 사용

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        
        if len(hand) % groupSize:
            return False
        
        count = collections.Counter(hand)
        minH = list(count.keys())
        
        # heapq.heapify(x) -> x를 힙 자료형으로 변환
        # heapq.heappush(x, y) -> x 힙에 y를 추가
        # heapq.heappop(x) -> x 힙의 가장 작은 원소를 pop하고 리턴
        heapq.heapify(minH) # 힙이 되지만 순서는 유지된다.
        
        while minH:
            first = minH[0]
    
            for i in range(first, first + groupSize):
                if i not in count:
                    return False
                count[i] -= 1
                if count[i] == 0:
                    if i != minH[0]:
                        return False
                    heapq.heappop(minH)
            
        return True

참고)
https://littlefoxdiary.tistory.com/3

profile
프론트 개발자 준비

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN