Skip to content

Commit aeb0595

Browse files
authored
Update 41-first-missing-positive.js
1 parent f1a8a88 commit aeb0595

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

41-first-missing-positive.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,31 @@ function swap(arr, i, j) {
4040
arr[i] = arr[j]
4141
arr[j] = tmp
4242
}
43+
44+
45+
// another
46+
47+
/**
48+
* @param {number[]} nums
49+
* @return {number}
50+
*/
51+
const firstMissingPositive = function(nums) {
52+
const n = nums.length
53+
for(let i = 0; i < n; i++) {
54+
while(nums[i] < n && nums[nums[i] - 1] !== nums[i]) {
55+
swap(nums, i, nums[i] - 1)
56+
}
57+
}
58+
59+
for(let i = 0; i < n; i++) {
60+
if(nums[i] !== i + 1) return i + 1
61+
}
62+
63+
return n + 1
64+
};
65+
66+
function swap(arr, i, j) {
67+
const tmp = arr[i]
68+
arr[i] = arr[j]
69+
arr[j] = tmp
70+
}

0 commit comments

Comments
 (0)