题目描述
判断能否将一个按升序排列的数组 nums
拆分成一个或多个连续的子序列。
Example:
Input: [1,2,3,3,4,5]
Output: True
Explanation:
You can split them into two consecutive subsequences :
1, 2, 3
3, 4, 5
解题思路
本题容易定位到用贪心算法去解决,但如何设计贪心策略是关键,难点是发现规律!
用一个计数器cnt
统计每个数字出现的次数,再用一个map
类型变量tails
, tails[i]
记录以数字i
为结尾的连续子序列的数目。遍历数组,当前数字为i
,首先试图将其放入以i-1
为结尾的子序列;如果不行,则该数字要作为新子序列的首个数字,将cnt[i+1]
、cnt[i+2]
减1,如果没有 i+1
、i+2
构成新序列,则原数组不能按要求拆分。
def isPossible(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
import collections
cnt = collections.Counter(nums)
tails = collections.defaultdict(int)
for num in nums:
if cnt[num] <= 0:
continue
cnt[num] -= 1
if tails[num-1] > 0:
tails[num] += 1
tails[num-1] -= 1
elif cnt[num+1] and cnt[num+2]:
cnt[num+1] -= 1
cnt[num+2] -= 1
tails[num+2] += 1
else:
return False
return True