LeetCodeEasy-【面試題61. 撲克牌中的順子】

從撲克牌中隨機抽5張牌,判斷是不是一個順子,即這5張牌是不是連續的。2~10爲數字本身,A爲1,J爲11,Q爲12,K爲13,而大、小王爲 0 ,可以看成任意數字。A 不能視爲 14。

示例 1:
輸入: [1,2,3,4,5]
輸出: True

示例 2:
輸入: [0,0,1,2,5]
輸出: True

限制:
數組長度爲 5
數組的數取值爲 [0, 13] .

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路1:暴力

先對list進行排序,然後統計大小王(萬能牌)的數量,然後遍歷一遍,看是否連續,不聯繫的地方萬能牌是否足夠補充好。
在這裏插入圖片描述

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        wn = 0
        nums.sort()
        print(nums)
        cnt = 0
        for num in nums:
            # print(cnt, num, wn)
            if num == 0:
                wn += 1
            elif cnt == 0:
                cnt = num
            else:
                if cnt == num - 1:
                    cnt = num
                elif num - cnt - 1 > 0 and num - cnt - 1 <= wn:
                    wn = wn - (num - cnt - 1)
                    cnt = num
                    # print((num - cnt - 1))
                else:
                    return False
            
        return True

思路2:題解 set/排序

在這裏插入圖片描述
在這裏插入圖片描述

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        repeat = set()
        ma, mi = 0, 14
        for num in nums:
            if num == 0: continue # 跳過大小王
            ma = max(ma, num) # 最大牌
            mi = min(mi, num) # 最小牌
            if num in repeat: return False # 若有重複,提前返回 false
            repeat.add(num) # 添加牌至 Set
        return ma - mi < 5 # 最大牌 - 最小牌 < 5 則可構成順子 

作者:jyd
鏈接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/solution/mian-shi-ti-61-bu-ke-pai-zhong-de-shun-zi-ji-he-se/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。

在這裏插入圖片描述

class Solution:
    def isStraight(self, nums: List[int]) -> bool:
        joker = 0
        nums.sort() # 數組排序
        for i in range(4):
            if nums[i] == 0: joker += 1 # 統計大小王數量
            elif nums[i] == nums[i + 1]: return False # 若有重複,提前返回 false
        return nums[4] - nums[joker] < 5 # 最大牌 - 最小牌 < 5 則可構成順子

作者:jyd
鏈接:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof/solution/mian-shi-ti-61-bu-ke-pai-zhong-de-shun-zi-ji-he-se/
來源:力扣(LeetCode)
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章