Appearance
645. 错误的集合
原题链接:LeetCode 645. 错误的集合
题目描述
集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复 。
给定一个数组 nums 代表了该集合发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。
示例 1:
- 输入: nums =
[1,2,2,4] - 输出:
[2,3]
示例 2:
- 输入: nums =
[1,1] - 输出:
[1,2]
提示:
- 2 <= nums.length <= 104
- 1 <=
nums[i]<= 104
难度: Easy
题解代码
javascript
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function(nums) {
const hash = {}
let repeat = miss = 0
for (let i = 0; i < nums.length; i ++) {
if (nums[i] in hash) {
repeat = nums[i]
} else {
hash[nums[i]] = 1
}
}
for (i = 1; i < nums.length + 1; i++) {
if (!(i in hash)) miss = i
}
return [repeat, miss]
};