Skip to content

Commit 821f013

Browse files
committed
645. 错误的集合
1 parent 3b3c402 commit 821f013

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
|617|[合并二叉树](https://leetcode.cn/problems/merge-two-binary-trees/)|[JavaScript](./algorithms/merge-two-binary-trees.js)|Easy|
8282
|628|[三个数的最大乘积](https://leetcode.cn/problems/maximum-product-of-three-numbers/)|[JavaScript](./algorithms/maximum-product-of-three-numbers.js)|Easy|
8383
|637|[二叉树的层平均值](https://leetcode.cn/problems/average-of-levels-in-binary-tree/)|[JavaScript](./algorithms/average-of-levels-in-binary-tree.js)|Easy|
84+
|645|[错误的集合](https://leetcode.cn/problems/set-mismatch/)|[JavaScript](./algorithms/set-mismatch.js)||Easy|
8485
|687|[最长同值路径](https://leetcode.cn/problems/longest-univalue-path/)|[JavaScript](./algorithms/longest-univalue-path.js)|Medium|
8586
|700|[二叉搜索树中的搜索](https://leetcode.cn/problems/search-in-a-binary-search-tree/)|[JavaScript](./algorithms/search-in-a-binary-search-tree.js)|Easy|
8687
|704|[二分查找](https://leetcode.cn/problems/binary-search/)|[JavaScript](./algorithms/binary-search.js)|Easy|

algorithms/set-mismatch.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {number[]}
4+
*/
5+
var findErrorNums = function (nums) {
6+
const map = new Map();
7+
const result = [];
8+
9+
// 思路:
10+
// 在「哈希表」中出现 2 次的为重复元素,未在「哈希表」中出现的元素为缺失元素
11+
// 在 [1, n] 中查询未出现的元素
12+
13+
// 统计每个数出现的次数
14+
for (let i = 0; i < nums.length; i++) {
15+
const curr = nums[i];
16+
if (map.has(curr)) {
17+
const count = map.get(curr);
18+
map.set(curr, count + 1);
19+
// 重复元素
20+
result.push(curr);
21+
} else {
22+
map.set(curr, 1);
23+
}
24+
}
25+
26+
for (let i = 1; i <= nums.length; i++) {
27+
if (!map.has(i)) {
28+
// 缺失元素
29+
result.push(i);
30+
break;
31+
}
32+
}
33+
34+
return result;
35+
};

0 commit comments

Comments
 (0)