集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums 代表了集合 S 发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
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.
示例 1:
输入:nums = [1,2,2,4]
输出:[2,3]
示例 2:
输入:nums = [1,1]
输出:[1,2]
提示:
2 <= nums.length <= 104
1 <= nums[i] <= 104
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function (nums) {
nums.sort((a, b) => a - b)//将数组进行排序
const res = new Array(2).fill(0);
let len = nums.length
for (let i = 0; i < len; i++) {
if (i + 1 < len && nums[i] == nums[i + 1]) {
res[0] = nums[i]//当两个相邻的数据相同时,此时找到重复值
}
if (nums.indexOf(i + 1) == -1) {
res[1] = i + 1//根据题意,数组应该是1~n的数组,所以当范围内的数字在数组中不存在时,找到缺少的数据
}
if (res[0] && res[1]) {
break
}
}
return res
};