https://leetcode.com/problems/find-all-duplicates-in-an-array/description/
Solution 1. swap number i to index i-1
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
int i=0;
while(i<nums.size()) {
if(nums[i] != nums[nums[i]-1])
swap(nums[i], nums[nums[i]-1]);
else i++;
}
for(int i=0; i<nums.size(); i++) {
if(i+1 != nums[i]) res.push_back(nums[i]);
}
return res;
}
Solution 2. Mark by +/-
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
for(int i=0; i<nums.size(); i++) {
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
if(nums[abs(nums[i])-1]>0) res.push_back(abs(nums[i]));
}
return res;
}
Solution 3. counting number nums[i] by adding n to index i-1
vector<int> findDuplicates(vector<int>& nums) {
vector<int> res;
int n = nums.size();
for(int i=0; i<n; i++) {
nums[(nums[i]-1)%n] += n;
}
for(int i=0; i<n; i++) {
if(nums[i]>2*n) res.push_back(i+1);
}
return res;
}
No comments:
Post a Comment