C++ with unordered_map


  • 0
    J

    I believe this is a very intuitive solution, but definitely not the best one as it requires O(n) extra space.

    class Solution {
    public:
        vector<int> findDuplicates(vector<int>& nums) {
            unordered_map<int, int> m;
            vector<int> res;
            for(int i = 0; i < nums.size(); i++) {
                ++m[nums[i]];
            }
            for(auto it = m.begin(); it != m.end(); ++it) {
                if(it->second == 2) {
                    res.push_back(it->first);
                }
            }
            return res;
        }
    };
    

Log in to reply
 

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