Skip to content

Latest commit

 

History

History
 
 

442. Find All Duplicates in an Array

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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]

Related Topics:
Array

Similar Questions:

Solution 1.

// OJ: https://leetcode.com/problems/find-all-duplicates-in-an-array/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    vector<int> findDuplicates(vector<int>& A) {
        vector<int> ans;
        int i = 0, N = A.size();
        while (i < N) {
            if (A[i] == 0 || A[i] == i + 1) ++i;
            else if (A[i] == A[A[i] - 1]) {
                ans.push_back(A[i]);
                A[i++] = 0;
            } else swap(A[i], A[A[i] - 1]);
        }
        return ans;
    }
};