LeetCode 659. Split Array into Consecutive Subsequences 题解

LeetCode 659. Split Array into Consecutive Subsequences

题目描述

判断能否将一个按升序排列的数组 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+1i+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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值