Description:

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

Code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Solution { public: vector<int> findDuplicates(vector<int>& nums) { vector<int> result; for (int i = 0; i < nums.size();i++) { if (nums[i]!= i+1) { while (nums[nums[i] - 1] != nums[i]) swap(nums[i], nums[nums[i] - 1]); } } for (int i = 0; i < nums.size();i++) { if (nums[i]!= i+1) result.push_back(nums[i]); } return result; } }; |

Time & Space:

O(n) & O(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;

}

};