[LeetCode] Find All Duplicates in an Array

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]

给定一个数组,其中的每个元素都小于数组的大小。这些元素中有些元素重复出现2次,有些只出现1次。

要求找出哪些出现了2次的元素值,并把这些值放入数组并返回。

思路:使用一个hashmap来存储数组中元素的索引的关系,key存储元素值,value存储索引。

利用hashmap中key的唯一性,如果其中有重复的元素值,就可以很容易找出来。

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int> res;
        unordered_map<int, int> m;
        for (int i = 0; i < nums.size(); i++) {
            if (!m.count(nums[i])) {
                m[nums[i]] = i;
                continue;
            }
            res.push_back(nums[i]);
        }
        return res;
        
    }
};
// 165 ms

 

posted @ 2018-01-19 14:09  immjc  阅读(110)  评论(0编辑  收藏  举报