Skip to content

Commit 6c9d9fd

Browse files
committed
Add solution #41
1 parent 3230038 commit 6c9d9fd

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
27|[Remove Element](./0027-remove-element.js)|Easy|
1818
31|[Next Permutation](./0031-next-permutation.js)|Medium|
1919
36|[Valid Sudoku](./0036-valid-sudoku.js)|Medium|
20+
41|[First Missing Positive](./0041-first-missing-positive.js)|Hard|
2021
43|[Multiply Strings](./0043-multiply-strings.js)|Medium|
2122
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
2223
58|[Length of Last Word](./0058-length-of-last-word.js)|Easy|
+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* 41. First Missing Positive
3+
* https://leetcode.com/problems/first-missing-positive/
4+
* Difficulty: Hard
5+
*
6+
* Given an unsorted integer array nums, return the smallest missing positive integer.
7+
*
8+
* You must implement an algorithm that runs in O(n) time and uses constant extra space.
9+
*/
10+
11+
/**
12+
* @param {number[]} nums
13+
* @return {number}
14+
*/
15+
var firstMissingPositive = function(nums) {
16+
let i = 0;
17+
18+
while (i < nums.length) {
19+
if (nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]) {
20+
[nums[nums[i] - 1], nums[i]] = [nums[i], nums[nums[i] - 1]];
21+
} else {
22+
i++;
23+
}
24+
}
25+
26+
for (i = 0; i < nums.length; i++) {
27+
if (nums[i] !== i + 1) {
28+
return i + 1;
29+
}
30+
}
31+
32+
return i + 1;
33+
};

0 commit comments

Comments
 (0)