-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path41.first-missing-positive.js
49 lines (47 loc) · 1.18 KB
/
41.first-missing-positive.js
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
42
43
44
45
46
47
48
49
/*
* @lc app=leetcode id=41 lang=javascript
*
* [41] First Missing Positive
*/
// @lc code=start
/**
* @param {number[]} nums
* @return {number}
*/
function placeCorrect(nums, index) {
let elementToBePlacedAtIndex = nums[index];
let displacedValue = nums[elementToBePlacedAtIndex - 1];
nums[elementToBePlacedAtIndex - 1] = elementToBePlacedAtIndex;
nums[index] = displacedValue;
if (
displacedValue > 0 &&
displacedValue < nums.length &&
elementToBePlacedAtIndex != displacedValue
) {
placeCorrect(nums, index);
}
}
var firstMissingPositive = function (nums) {
let length = nums.length;
for (let i = 0; i < length; i++) {
if (nums[i] < 0 || nums[i] > length) {
nums[i] = 0;
}
}
for (let i = 0; i < length; i++) {
if (nums[i] > 0 && nums[i] < length && nums[i] - 1 !== i) {
placeCorrect(nums, i);
}
}
if (length === 1 && nums[0] === 0) return 1;
if (length === 1 && nums[0] === 1) return 2;
for (let i = 0; i < length; i++) {
if (i !== nums[i] - 1) return i + 1;
}
return length + 1;
};
//[7,8,9,11,12]
// @lc code=end
// @after-stub-for-debug-begin
module.exports = firstMissingPositive;
// @after-stub-for-debug-end