程式語言 - LeetCode - C++ - 659. Split Array into Consecutive Subsequences



題目:


解答:

class Solution {
public:
    bool isPossible(vector<int>& nums) {
        int n = nums.size();
        unordered_map<int, int> freq;
        unordered_map<int, int> need;

        for (int x : nums) {
            freq[x] += 1;
        }

        for (int x : nums) {
            if (freq[x] == 0) {
                continue;
            }

            if (need[x] > 0) {
                freq[x] -= 1;
                need[x] -= 1;
                need[x + 1] += 1;
            }
            else if (freq[x + 1] > 0 && freq[x + 2] > 0) {
                freq[x] -= 1;
                freq[x + 1] -= 1;
                freq[x + 2] -= 1;
                need[x + 3] += 1;
            }
            else {
                return false;
            }
        }

        return true;
    }
};