# 645. Set Mismatch

The set `S` originally contains numbers from 1 to `n`. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

Given an array `nums` representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

Example 1:

``````Input: nums = [1,2,2,4]
Output: [2,3]
``````

Note:

1. The given array size will in the range [2, 10000].
2. The given array’s numbers won’t have any order.

``````class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> res(2, 0), cnt(nums.size(), 0);
for (int num : nums) ++cnt[num - 1];
for (int i = 0; i < cnt.size(); ++i) {
if (res[0] != 0 && res[1] != 0) return res;
if (cnt[i] == 2) res[0] = i + 1;
else if (cnt[i] == 0) res[1] = i + 1;
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
vector<int> res(2, -1);
for (int i : nums) {
if (nums[abs(i) - 1] < 0) res[0] = abs(i);
else nums[abs(i) - 1] *= -1;
}
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] > 0) res[1] = i + 1;
}
return res;
}
};
``````

``````class Solution {
public:
vector<int> findErrorNums(vector<int>& nums) {
for (int i = 0; i < nums.size(); ++i) {
while (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) return {nums[i], i + 1};
}
}
};
``````

Find the Duplicate Number

https://discuss.leetcode.com/topic/96808/java-o-n-time-o-1-space

https://discuss.leetcode.com/topic/97091/c-6-lines-solution-with-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation