[Leetcode]659.Split Array into Consecutive Subsequences

链接:LeetCode659

输入一个按升序排序的整数数组(可能包含重复数字),你需要将它们分割成几个子序列,其中每个子序列至少包含三个连续整数。返回你是否能做出这样的分割?

示例 1:

输入: ([1,2,3,3,4,5])
输出: True
解释:
你可以分割出这样两个连续子序列 :
1, 2, 3
3, 4, 5

相关标签:贪心

一般来说,贪心的题目是写起来最简单,想起来最难的。这里我们考虑是否能分割出多个连续子序列:在遍历构造连续子序列时,考虑一个数的位置,只有两种情况:要么加在之前的某个序列后面,要么自己新建一个子序列;如果都不行,则说明无法做出分割。
首先,我们将所有数存入哈希表count,其中键为数值,值为该数个数;在构建一个哈希表need,代表我们可以加入已知子序列后的数。那么我们在遍历每一个数n时,我们要分以下情况:

  • 当count[n]==0,说明该数已经被用完了,继续即可。
  • 当该数在need哈希表中,说明该数可以加入已知子序列中,则need[n]-=1;并且此时我们再加入该子序列时,则应该为n+1,所以need[n+1]+=1;
  • 当其上条件不满足,则需要重建一个子序列,那么当前仅当n+1和n+2存在时,才能新建一个子序列,否则返回False即可。
    代码如下:

python:

import collections
class Solution:
    def isPossible(self, nums: List[int]) -> bool:
        need = collections.defaultdict(int)
        count = collections.Counter(nums)
        for n in nums:
            if not count[n]:
                continue
            elif need[n]:
                need[n] -= 1
                need[n+1] += 1
            elif count[n+1]>0 and count[n+2]>0:
                count[n+1] -= 1
                count[n+2] -= 1
                need[n+3] +=1
            else:
                return False
            count[n] -=1
        return True

C++:

class Solution {
public:
    bool isPossible(vector<int>& nums) {
        map<int,int> count;
        map<int,int> need;
        for(int n:nums) count[n]++;
        for(int n:nums){
            if(count[n]==0){
                continue;
            }
            else if(need[n]>0){
                need[n]--;
                need[n+1]++;
            }
            else if (count[n+1]>0 && count[n+2]>0){
                count[n+1]--;
                count[n+2]--;
                need[n+3]++;
            }
            else{
                return false;
            }
            count[n] --;
        }
        return true;
    }
};
原文地址:https://www.cnblogs.com/hellojamest/p/12245640.html