Given an integer array A, where 1≤a[i]≤n (n is an array length), where some elements occur two times and other elements appear once.
Find all elements that appear two times.
Can you solve this problem without going into any extra space and in O (n) time complexity?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
See: https://leetcode.com/problems/find-all-duplicates-in-an-array/description/
C++:
Method One:
Class Solution {public: vector<int> findduplicates (vector<int>& nums) { vector<int> res; for (int i=0;i<nums.size (); ++i) { int idx=abs (nums[i])-1; if (nums[idx]<0) { res.push_back (idx+1); } NUMS[IDX]=-NUMS[IDX]; } return res; }};
Method Two:
Class Solution {public: vector<int> findduplicates (vector<int>& nums) { Vector<int > res; for (int i = 0; i < nums.size (); ++i) { if (nums[i]! = Nums[nums[i]-1]) { swap (nums[i], nums[nums[i] -1]); -----;} } for (int i = 0; i < nums.size (); ++i) { if (nums[i]! = i + 1) { res.push_back (nums[i]); } } return res; }};
Reference: https://www.cnblogs.com/grandyang/p/6209746.html
442 Find all duplicates in an array of duplicate data