#Leetcode# 442. Find All Duplicates in an Array

https://leetcode.com/problems/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]

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int len = nums.size();
        vector<int> v;
        for(int i = 0; i < len; i ++) {
            int temp = abs(nums[i]) - 1;
            if(nums[temp] < 0) v.push_back(temp + 1);
            nums[temp] = -nums[temp];
        }
        return v;
    }
};

  

posted @ 2019-12-26 19:14  丧心病狂工科女  阅读(127)  评论(0编辑  收藏  举报