Java

• import java.util.ArrayList;
import java.util.List;

/**

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?

Example:
Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

*/

public class Find_All_Duplicates_in_an_Array {

class Solution {
public List<Integer> findDuplicates(int[] nums) {

List<Integer> result = new ArrayList<>();

if (nums == null || nums.length == 0) {
return result;
}

for (int i = 0; i < nums.length; i++) {

// when find a number i, flip the number at position i-1 to negative.
// if the number at position i-1 is already negative, i is the number that occurs twice.

int index = Math.abs(nums[i]) - 1;

if (nums[index] < 0) {
//                    nums[i] *= (-1);
}

nums[index] *= (-1);
}

return result;
}
}
}

• // OJ: https://leetcode.com/problems/find-all-duplicates-in-an-array/
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> findDuplicates(vector<int>& A) {
vector<int> ans;
int i = 0, N = A.size();
while (i < N) {
if (A[i] == 0 || A[i] == i + 1) ++i;
else if (A[i] == A[A[i] - 1]) {
ans.push_back(A[i]);
A[i++] = 0;
} else swap(A[i], A[A[i] - 1]);
}
return ans;
}
};

• class Solution(object):
def findDuplicates(self, nums):
ans = []
for i in range(0, len(nums)):
while nums[nums[i] - 1] != nums[i]:
tmp = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
nums[i] = tmp
for i in range(0, len(nums)):
if i + 1 != nums[i]:
ans.append(nums[i])
return ans



Java

• class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> duplicates = new ArrayList<Integer>();
for (int num : nums) {
num = Math.abs(num);
if (nums[num - 1] < 0)
else
nums[num - 1] *= -1;
}
return duplicates;
}
}

• // OJ: https://leetcode.com/problems/find-all-duplicates-in-an-array/
// Time: O(N)
// Space: O(1)
class Solution {
public:
vector<int> findDuplicates(vector<int>& A) {
vector<int> ans;
int i = 0, N = A.size();
while (i < N) {
if (A[i] == 0 || A[i] == i + 1) ++i;
else if (A[i] == A[A[i] - 1]) {
ans.push_back(A[i]);
A[i++] = 0;
} else swap(A[i], A[A[i] - 1]);
}
return ans;
}
};

• class Solution(object):
def findDuplicates(self, nums):
ans = []
for i in range(0, len(nums)):
while nums[nums[i] - 1] != nums[i]:
tmp = nums[nums[i] - 1]
nums[nums[i] - 1] = nums[i]
nums[i] = tmp
for i in range(0, len(nums)):
if i + 1 != nums[i]:
ans.append(nums[i])
return ans