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

120 篇文章 0 订阅

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
                
        

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值