c++ greedy


  • 0
    B
    class Solution {
    public:
        bool isPossible(vector<int>& nums) {
            unordered_map<int, int> hash;
            unordered_map<int, int> seq;
            for(auto n : nums) hash[n]++;
            for (int i=0; i<nums.size(); i++) {
                if (hash[nums[i]] == 0) continue;
                else if (seq.find(nums[i]-1) != seq.end() && seq[nums[i]-1] != 0) {
                    seq[nums[i]-1]--;
                    seq[nums[i]]++;
                }
                else if (hash.find(nums[i]+1) != hash.end() && hash.find(nums[i]+2) != hash.end()
                    && hash[nums[i]+1] != 0 && hash[nums[i]+2] != 0) {
                        seq[nums[i]+2]++;
                        hash[nums[i]+1]--;
                        hash[nums[i]+2]--;
                }
                else return false;
                hash[nums[i]]--;
            }
            return true;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.