剑指offer-61

从扑克牌中随机抽5张牌,判断是不是一个顺子,即这5张牌是不是连续的。2~10为数字本身,A为1,J为11,Q为12,K为13,而大、小王为 0 ,可以看成任意数字。A 不能视为 14。来源:LeetCode:https://leetcode-cn.com/problems/bu-ke-pai-zhong-de-shun-zi-lcof

限制:数组长度为 5 数组的数取值为 [0, 13] .

example :输入: [1,2,3,4,5]       输入: [0,0,1,2,5]
      输出: True             输出: True

 我的题解:统计0的个数,以及多递增(超过1)的和: eg 1-(3,5)-5-3-1=1,多了1,需要1个0来抵消;最后看0的个数能否大于多递增的数值

 1 class Solution:
 2     def isStraight(self, nums: List[int]) -> bool:
 3         surplus, zero, flag = 0,0,0 #元素差值,0的个数,第一个不为0的元素的下标
 4         nums = sorted(nums)
 5         for index,i in enumerate(nums):#统计0的个数并找到第一个不为0的元素
 6             if i == 0:
 7                 zero += 1
 8             else:
 9                 pre = nums[index]
10                 flag = index + 1
11                 break
12         for index,i in enumerate(nums[flag:]):
13             if i == pre:
14                 return False
15             surplus += i - pre - 1
16             pre = i
17         if surplus <= zero:
18             return True
19         else:
20             return False
View Code

官方题解:

方法一: 集合 Set + 遍历 作者: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/

 1 class Solution:
 2     def isStraight(self, nums: List[int]) -> bool:
 3         repeat = set()
 4         ma, mi = 0, 14
 5         for num in nums:
 6             if num == 0: continue # 跳过大小王
 7             ma = max(ma, num) # 最大牌
 8             mi = min(mi, num) # 最小牌
 9             if num in repeat: return False # 若有重复,提前返回 false
10             repeat.add(num) # 添加牌至 Set
11         return ma - mi < 5 # 最大牌 - 最小牌 < 5 则可构成顺子 
View Code

方法二:排序 + 遍历

1 class Solution:
2     def isStraight(self, nums: List[int]) -> bool:
3         joker = 0
4         nums.sort() # 数组排序
5         for i in range(4):
6             if nums[i] == 0: joker += 1 # 统计大小王数量
7             elif nums[i] == nums[i + 1]: return False # 若有重复,提前返回 false
8         return nums[4] - nums[joker] < 5 # 最大牌 - 最小牌 < 5 则可构成顺子
View Code



原文地址:https://www.cnblogs.com/dolphin-bamboo/p/14199662.html