【python3】leetcode 846. Hand of Straights (Medium)

时间:2019-01-09
本文章向大家介绍【python3】leetcode 846. Hand of Straights (Medium),主要包括【python3】leetcode 846. Hand of Straights (Medium)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

846. Hand of Straights

Alice has a hand of cards, given as an array of integers.

Now she wants to rearrange the cards into groups so that each group is size W, and consists of Wconsecutive cards.

Return true if and only if she can.

 

Example 1:

Input: hand = [1,2,3,6,2,3,4,7,8], W = 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], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.

题目要求卡牌数能平分成每份W张牌,且每份都是连续的数

1 my solution 

刚开始很容易就想到count,但是由于我不想用额外空间,所以直接sort 遍历,一共有len / W 份

记turn = len /W

每轮w张牌都满足连续条件的话就删掉,所以hand[0]永远是最小的,所以每份W张都是 hand[0],hand[0]+1,...,hand[0]+W-1

class Solution:
    def isNStraightHand(self, hand, W):
        """
        :type hand: List[int]
        :type W: int
        :rtype: bool
        """
        if len(hand) % W !=0: return False
        turn = len(hand) / W
        hand.sort()
        while(turn >0 ):
            a = hand[0]
            for i in range(1,W):
                if a+i not in hand:return False
                else:del hand[hand.index(a+i)]
            del hand[hand.index(a)]
            turn -= 1
            
        return True

 2 暴力破解

class Solution:
    def isNStraightHand(self, hand, W):
        """
        :type hand: List[int]
        :type W: int
        :rtype: bool
        """

        count = collections.Counter(hand)
        if sum(list(count.values())) % W !=0:return False
        while count:
            minx = min(count)
            for i in range(1,W):
                if not count.get(minx + i):return False
                else:
                    count[minx + i] -= 1
                    if count[minx + i] == 0:del count[minx + i]
            count[minx] -= 1
            if count[minx] == 0:del count[minx]
        return len(count) == 0