442. Find All Duplicates in an Array
code:
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
ostream & operator<<(ostream &out, vector<int> &A) {
for (vector<int>::iterator i = A.begin(); i != A.end(); i++)
out << *i << ' ';
return out;
}
class Solution {
public:
//用正负来标记是否出现过
vector<int> findDuplicates(vector<int>& nums) {
vector<int> dup;
for (int i = 0; i < nums.size(); i++) {
if (nums[abs(nums[i])-1] > 0)
nums[abs(nums[i])-1] = -nums[abs(nums[i])-1];
else
dup.push_back(abs(nums[i])); //如果nums[i]-1索引到的数为负数,则nums[i]有重
}
return dup;
}
};
int main () {
int n;
while (cin >> n) {
vector<int> nums;
while (n--) {
int a;
cin >> a;
nums.push_back(a);
}
Solution sol;
sol.findDuplicates(nums);
cout << endl;
}
return 0;
}