Description:

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

Code:

 

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

1 comments

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

*