题目:659. Split Array into Consecutive Subsequences
https://leetcode.com/problems/split-array-into-consecutive-subsequences/
You are given an integer array sorted in ascending order (may contain duplicates), you need to split them into several subsequences, where each subsequences consist of at least 3 consecutive integers. Return whether you can make such a split.
Examples:
Example 1:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3
3, 4, 5
Example 2:
Input: [1,2,3,3,4,4,5,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3, 4, 5
3, 4, 5
Example 3:
Input: [1,2,3,4,4,5]
Output: False
题目大意:
就是打牌,把手上的牌从小按大理好,现在要排顺子,顺子的要求就是要连续超过3张牌
思路:
斗过地主都知道,理顺子最好就是最大限度使用重复的牌减少单张牌的概率而且尽可能连长这样别人不好压你。那么就是说,我们先按规则建了一个3张牌的顺子,然后看看有没有第4张牌连上来,看看有没有第5张牌连上来,只要有就一直连,连到没有。
按照这个思路,我们先看看三个牌有吗,没有就错了,如果有,个么第四张牌的位置就可以多一个了。
用count 来统计每张牌多少,用tail来给尾巴上连起来的牌的占位。
class Solution:
def isPossible(self, nums: List[int]) -> bool:
count=collections.Counter(nums)
tails=collections.Counter()
for x in nums:
if count[x] == 0:
continue
elif tails[x] > 0:
tails[x] -=1
tails[x+1] +=1
elif count[x+1] > 0 and count[x+2] > 0:
count[x+1] -=1
count[x+2] -=1
tails[x+3] +=1
else:
return False
count[x] -=1
return True