645.问题的集合(javascript)645.SetMismatch
原创集合 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
};
leetcode: https://leetcode.cn/problems/set-mismatch/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



