topic
Randomly draw 5 cards from the playing cards to determine if it is a straight, that is, if the 5 cards are consecutive. 2~10 are the numbers themselves, A is 1, J is 11, Q is 12, K is 13, and the big and small kings are 0, which can be regarded as any number. A cannot be regarded as 14.
Example 1:
Input: [1,2,3,4,5]
Output: True
Example 2:
Input: [0,0,1,2,5]
Output: True
Ideas
Big and small kings can be regarded as arbitrary numbers, so we will regard them as 0 first.
The most intuitive way to judge whether the five numbers are continuous is to sort the array. Since 0 can be any number, we can use 0 to fill the gaps in the array. If the sorted array is not continuous, as long as we have enough 0 to fill the gap, the number is actually continuous.
Three things to do:
1. Count the number of 0s in
the array 2. Count the number of vacancies between adjacent numbers in the array after sorting
3. If the total number of vacancies is less than or equal to the number of 0, then the array is continuous. Otherwise it is not continuous.
Note: If non-zero numbers appear repeatedly, the array is not continuous.
Code
class Solution:
def isStraight(self, nums: List[int]) -> bool:
nums.sort()
zero_count,gap_count=0,0
for num in nums:
if num==0: zero_count+=1
else: break
small = zero_count
big = small+1
while small<big and big<len(nums):
if nums[small]==nums[big]: return False
gap_count = nums[big]-nums[small]-1
small = big
big+=1
if gap_count>zero_count:return False
return True
the complexity
Time complexity O(nlogn): where N is the length of nums, and the array sorting uses O(nlogn) time.
Space complexity O(1)