[LeetCode] 442. Find All Duplicates in an Array (C++)

版权声明:本文为博主原创文章,未经博主允许不得转载。@ceezyyy11 https://blog.csdn.net/ceezyyy11/article/details/88935633

[LeetCode] 442. Find All Duplicates in an Array (C++)

Medium

Share
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]

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        map<int,int> occurences;
        vector<int> res;
        vector<int>::iterator it;
        int i;
        for(it=nums.begin();it!=nums.end();it++) {
            occurences[*it]++;
            if(occurences[*it]==2) {
                res.push_back(*it);
            }
        }
        return res;   
    }
};


/*
Submission Detail:

Runtime: 228 ms, faster than 5.30% of C++ online submissions for Find All Duplicates in an Array.
Memory Usage: 27.9 MB, less than 6.57% of C++ online submissions for Find All Duplicates in an Array.

*/

猜你喜欢

转载自blog.csdn.net/ceezyyy11/article/details/88935633