LeetCode 442. Find All Duplicates in an Array

Description:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

Solution:

Set 去重

vector<int> findDuplicates(vector<int>& nums) {
        vector<int> re;
        set<int> s;
        set<int>::iterator it;
        for (int j : nums) {
            it = s.find(j);
            if (it == s.end())
                s.insert(j);
            else
                re.push_back(j);
        }

    return re;
}

你可能感兴趣的:(LeetCode)