442. Find All Duplicates in an Array

Description: https://leetcode.com/problems/find-all-duplicates-in-an-array/description/ Code:  

Time & Space: O(n) & O(1)

One thought on “442. Find All Duplicates in an Array”

  1. Here is a better solution:

    class Solution {
    public:
    // Time: O(N), Space: O(1)
    // mark used number as the opposite
    vector findDuplicates(vector& nums) {
    vector ans;
    for (int i = 0; i < nums.size(); ++i) {
    int j = abs(nums[i]) – 1;
    int& x = nums[j];
    if (x < 0) ans.push_back(j + 1);
    x = -x;
    }
    return ans;
    }
    };

Leave a Reply

Your email address will not be published. Required fields are marked *