442. Find All Duplicates in an Array
Difficulty: Medium
Topics: Array
Similar Questions:
Problem:
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
</p>Example:
Input: [4,3,2,7,8,2,3,1]
Output: [2,3] </pre>
Solutions:
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> ret;
for (int i = 0; i < nums.size(); ++i) {
int kickOut = 0;
swap(kickOut, nums[i]);
while (kickOut != 0 && nums[kickOut - 1] != kickOut) {
swap(kickOut, nums[kickOut - 1]);
}
if (kickOut != 0) {
ret.push_back(kickOut);
}
}
return ret;
}
};