「每日LeetCode」2022年6月28日

本文最后更新于:2023年3月19日 晚上

645.错误的集合

645.错误的集合

Category Difficulty Likes Dislikes
algorithms Easy (41.78%) 272 -

Tags
Companies
集合 s 包含从 1 到 n 的整数。不幸的是,因为数据错误,导致集合里面某一个数字复制了成了集合里面的另外一个数字的值,导致集合 丢失了一个数字 并且 有一个数字重复
给定一个数组 nums 代表了集合 S 发生错误后的结果。
请你找出重复出现的整数,再找到丢失的整数,将它们以数组的形式返回。

示例 1:
输入:nums = [1,2,2,4] 输出:[2,3]
示例 2:
输入:nums = [1,1] 输出:[1,2]

提示:

  • 2 <= nums.length <= 104
  • 1 <= nums[i] <= 104

Discussion | Solution

思路

先排序,如果第一个非 1,说明缺少的是 1,只需要找到第一个重复的数据即可。如果是 1,找到第一个下标不为 i+1 的数说明缺少的是它。如果最后都没有找到,说明缺少的是等于数组长度的那个数。

解答

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @lc app=leetcode.cn id=645 lang=javascript
*
* [645] 错误的集合
*/

// @lc code=start
/**
* @param {number[]} nums
* @return {number[]}
*/
var findErrorNums = function (nums) {
nums.sort((a, b) => +a - +b);
let prev = 0;
const res = [];
const length = nums.length;

if (nums[0] !== 1) res[1] = 1;

for (let i = 0; i < nums.length; i++) {
const num = nums[i];
if (typeof res[0] !== "number" && num === prev) {
res[0] = num;
nums.splice(i, 1);
i--;
continue;
}
if (typeof res[1] !== "number" && num !== i + 1) {
res[1] = i + 1;
}

if (typeof res[1] === "number" && typeof res[0] === "number") {
return res;
}

prev = num;
}
typeof res[1] !== "number" && (res[1] = length);
return res;
};
// @lc code=end