You have a set of integers s, which originally contains all the numbers from 1 to n. Unfortunately, due to some error, one of the numbers in s got duplicated to another number in the set, which results in repetition of one number and loss of another number.
You are given an integer array nums representing the data status of this set after the error.
Find the number that occurs twice and the number that is missing and return them in the form of an array.
Since the 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. After sorting, the index where the value does not match the index + 1 gives us the duplicate and missing numbers.
classSolution {
public: vector<int> findErrorNums(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]);
}
}
for (int i =0; i < n; ++i) {
if (nums[i] != i +1) return {nums[i], i +1};
}
return {};
}
};
classSolution {
publicint[]findErrorNums(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;
}
}
for (int i = 0; i < n; i++) {
if (nums[i]!= i + 1) returnnewint[]{nums[i], i + 1};
}
returnnewint[0];
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deffindErrorNums(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]
for i, v in enumerate(nums):
if v != i +1:
return [v, i +1]
return []
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funfindErrorNums(nums: IntArray): IntArray {
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
}
}
for (i in0 until n) {
if (nums[i] != i + 1) return intArrayOf(nums[i], i + 1)
}
return intArrayOf()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
functionfindErrorNums(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;
}
}
for (leti=0; i<n; i++) {
if (nums[i] !==i+1) return [nums[i], i+1];
}
return [];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnfind_error_nums(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);
}
}
for (i, &v) in nums.iter().enumerate() {
if v != (i asi32) +1 {
returnvec![v, (i asi32) +1];
}
}
vec![]
}
}