2007. Find Original Array From Doubled Array

class Solution {

public:

    vector<int> findOriginalArray(vector<int>& changed) {

        int n = changed.size();

        if (n % 2 == 1) return {};

        sort(changed.begin(), changed.end());

        vector<int> ans;

        map<int, int> mp;

        for (int i = 0; i < n; i++) {

            mp[changed[i]]++;

        }

        for (int i = 0; i < n; i++) {

          if (mp[changed[i]] == 0) continue;

          if (mp[changed[i] * 2] == 0) return {};

          ans.push_back(changed[i]);

          mp[changed[i]]--;

          mp[changed[i] * 2]--;

        }

        return ans;

    }

};

Comments

Popular posts from this blog

1431. Kids With the Greatest Number of Candies

125. Valid Palindrome

771. Jewels and Stones