[LeetCode] Find All Duplicates in an Array

442. Find All Duplicates in an Array

Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i = 0; i < nums.size(); i++) {
nums[abs(nums[i]) - 1] *= -1;
if(nums[abs(nums[i]) - 1] > 0) res.push_back(abs(nums[i]));
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/29/PS/LeetCode/find-all-duplicates-in-an-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.