Skip to content

Commit b40c224

Browse files
committed
feat: add question 41
1 parent 939187a commit b40c224

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

41.缺失的第一个正数.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
* @lc app=leetcode.cn id=41 lang=javascript
3+
*
4+
* [41] 缺失的第一个正数
5+
*
6+
* 1. 先判断 1 是否为最终结果, 是则直接返回, 不是则把 1 作为标志位, 把 <= 0 和 > length 的位置都置为 1
7+
* 2. 以原数组作为索引表, 遍历数字, 将当前数字作为 index, 将 index 位置的数字置为负数, 表示存在
8+
* 因为是以负数为标志, 所以当前数字可能会是负数, 需要取绝对值才是原本数字
9+
* 如果当前数字等于 length, 不能更新 length 位置(超界了), 用一个单独标识存是否出现过这种情况
10+
* 3. 经过处理后, 从下标 2 开始查找(0 不符合要求, 1 已经作为标志位了, 如果 1 是结果, 在第 1 步就结束了)第一个大于 0 的数字, 下标即结果
11+
* 如果没找到, 则说明 1 ~ n-1 都是存在的, 结果只能是 n 或者 n + 1, 具体是哪个取决于第 2 步的额外标识 n 是否出现过
12+
*/
13+
14+
// @lc code=start
15+
/**
16+
* @param {number[]} nums
17+
* @return {number}
18+
*/
19+
var firstMissingPositive = function(nums) {
20+
let count = 0;
21+
for (let i = 0; i < nums.length; i++) {
22+
if (nums[i] === 1) {
23+
count++;
24+
}
25+
if (nums[i] < 1 || nums[i] > nums.length) {
26+
nums[i] = 1;
27+
}
28+
}
29+
30+
if (count === 0) {
31+
return 1;
32+
}
33+
if (nums.length === 1) {
34+
return 2;
35+
}
36+
37+
let hasN = false;
38+
for (let i = 0; i < nums.length; i++) {
39+
const n = Math.abs(nums[i]);
40+
if (n === nums.length) {
41+
hasN = true;
42+
} else {
43+
nums[n] = -Math.abs(nums[n]);
44+
}
45+
}
46+
47+
for (let i = 2; i < nums.length; i++) {
48+
if (nums[i] > 0) {
49+
return i;
50+
}
51+
}
52+
return nums.length + (hasN ? 1 : 0);
53+
};
54+
// @lc code=end

0 commit comments

Comments
 (0)