Given an integer array nums of length n where all the integers of nums are in the range [1, n] and each integer appears once or twice, return an array of all the integers that appears twice.
You must write an algorithm that runs in O(n) time and uses only constant extra space.
Since all numbers are in the range [1, n], we can use the array indices to place each number at its correct position (i.e., value v at index v-1). If a number is already at its correct position or a duplicate is found, we skip it. This way, duplicates will be left at positions where the value does not match the index + 1.
classSolution {
public: vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
for (int i =0; i < n; ++i) {
while (nums[i] != nums[nums[i] -1]) {
swap(nums[i], nums[nums[i] -1]);
}
}
vector<int> ans;
for (int i =0; i < n; ++i) {
if (nums[i] != i +1) ans.push_back(nums[i]);
}
return ans;
}
};
classSolution {
public List<Integer>findDuplicates(int[] nums) {
int n = nums.length;
for (int i = 0; i < n; i++) {
while (nums[i]!= nums[nums[i]- 1]) {
int tmp = nums[i];
nums[i]= nums[tmp - 1];
nums[tmp - 1]= tmp;
}
}
List<Integer> ans =new ArrayList<>();
for (int i = 0; i < n; i++) {
if (nums[i]!= i + 1) ans.add(nums[i]);
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
deffindDuplicates(self, nums: list[int]) -> list[int]:
n = len(nums)
for i in range(n):
while nums[i] != nums[nums[i] -1]:
nums[nums[i] -1], nums[i] = nums[i], nums[nums[i] -1]
return [v for i, v in enumerate(nums) if v != i +1]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funfindDuplicates(nums: IntArray): List<Int> {
val n = nums.size
for (i in0 until n) {
while (nums[i] != nums[nums[i] - 1]) {
val tmp = nums[i]
nums[i] = nums[tmp - 1]
nums[tmp - 1] = tmp
}
}
val ans = mutableListOf<Int>()
for (i in0 until n) {
if (nums[i] != i + 1) ans.add(nums[i])
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
functionfindDuplicates(nums: number[]):number[] {
constn=nums.length;
for (leti=0; i<n; i++) {
while (nums[i] !==nums[nums[i] -1]) {
consttmp=nums[i];
nums[i] =nums[tmp-1];
nums[tmp-1] =tmp;
}
}
constans: number[] = [];
for (leti=0; i<n; i++) {
if (nums[i] !==i+1) ans.push(nums[i]);
}
returnans;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
impl Solution {
pubfnfind_duplicates(nums: &mut Vec<i32>) -> Vec<i32> {
let n = nums.len();
for i in0..n {
while nums[i] != nums[(nums[i] -1) asusize] {
let j = (nums[i] -1) asusize;
nums.swap(i, j);
}
}
letmut ans = Vec::new();
for (i, &v) in nums.iter().enumerate() {
if v != (i asi32) +1 {
ans.push(v);
}
}
ans
}
}