leetcode 442. Find All Duplicates in an Array 重复元素查找

来源:互联网 发布:线性时间选择算法c语言 编辑:程序博客网 时间:2024/06/03 04:07

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]

题意很简单,直接使用set遍历查询即可

代码如下:

#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>using namespace std;class Solution {public:    vector<int> findDuplicates(vector<int>& nums)     {        vector<int> res;        set<int> ss;        for (int a : nums)        {            if (ss.find(a) == ss.end())                ss.insert(a);            else                res.push_back(a);        }        return res;    }};
原创粉丝点击