Skip to content

Commit 9bfd337

Browse files
authored
Update 41-first-missing-positive.js
1 parent 63d879c commit 9bfd337

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

41-first-missing-positive.js

+25
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,28 @@ const firstMissingPositive = function(nums) {
1515
}
1616
return max < 0 ? 1 : max + 1
1717
};
18+
19+
// another
20+
21+
/**
22+
* @param {number[]} nums
23+
* @return {number}
24+
*/
25+
function firstMissingPositive(nums) {
26+
const A = nums
27+
const n = nums.length
28+
for (let i = 0; i < n; i++) {
29+
while (A[i] > 0 && A[i] <= n && A[A[i] - 1] !== A[i]) swap(A, i, A[i] - 1)
30+
}
31+
32+
for (let i = 0; i < n; i++) {
33+
if (A[i] !== i + 1) return i + 1
34+
}
35+
return n + 1
36+
}
37+
38+
function swap(arr, i, j) {
39+
let tmp = arr[i]
40+
arr[i] = arr[j]
41+
arr[j] = tmp
42+
}

0 commit comments

Comments
 (0)