Leetcode每日一题:659.split-array-into-consecutive-subsequences(分割数组为连续子序列)

Leetcode每日一题:659.split-array-into-consecutive-subsequences(分割数组为连续子序列)_第1张图片
思路:看它贴的标签是贪心算法,我只想到了记录每个数出现的个数,并且还是数组,后来一想如果元素太大导致数组长度很长怎么办,老是想不到hash的方法,也没想到记录以nums[i]结尾的连续子序列个数;
贴上大佬的回答:
Leetcode每日一题:659.split-array-into-consecutive-subsequences(分割数组为连续子序列)_第2张图片
Leetcode每日一题:659.split-array-into-consecutive-subsequences(分割数组为连续子序列)_第3张图片
这里一定不要把tail[nums[i]+1]、tail[nums[i]+2] 和tail[nums[i+1]]、tail[nums[i+2]]混淆
Leetcode每日一题:659.split-array-into-consecutive-subsequences(分割数组为连续子序列)_第4张图片

class Solution {
     
public:
    bool isPossible(vector<int> &nums)
    {
     
        int len = nums.size();
        if (len < 3)
            return false;
        unordered_map<int, int> count; //记录每个数字出现的个数
        unordered_map<int, int> tail;  //记录以数字nums[i]结尾的子序列个数
        for (int i = 0; i < len; i++)
        {
     
            count[nums[i]]++;
        }
        for (int i = 0; i < len; i++)
        {
     
            if (count[nums[i]] == 0)
                continue;
            //优先考虑把nums[i]加到已存在的子序列中
            if (count[nums[i]] > 0 && tail[nums[i] - 1] > 0)
            {
     
                
                tail[nums[i] - 1]--;
                tail[nums[i]]++;
                count[nums[i]]--;
            }
            //没有子序列就让它们三个创建子序列
            else if (count[nums[i]] > 0 && count[nums[i] + 1] > 0 && count[nums[i] + 2] > 0)
            {
     
                tail[nums[i] + 2]++;
                count[nums[i]]--;
                count[nums[i] + 1]--;
                count[nums[i] + 2]--;
            }
            else
            {
     
                return false;
            }
        }
        return true;
    }
};

你可能感兴趣的:(Leetcode,算法,hash)