-
Notifications
You must be signed in to change notification settings - Fork 0
/
0041. First Missing Positive.js
70 lines (66 loc) · 1.18 KB
/
0041. 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Given an unsorted integer array, find the smallest missing positive integer.
//
// Example 1:
//
// Input: [1,2,0]
// Output: 3
//
// Example 2:
//
// Input: [3,4,-1,1]
// Output: 2
//
// Example 3:
//
// Input: [7,8,9,11,12]
// Output: 1
//
// Note:
//
// Your algorithm should run in O(n) time and uses constant extra space.
/**
* @param {number[]} nums
* @return {number}
*/
// Time O(n)
// Space O(1)
//
// Put each number in its right place.
// When we find n, then swap it with nums[n - 1].
// At last, the first place where its number is not right, return the place + 1.
//
// e.g. [3, 4, -1, 1]
//
// i = 0
// nums = [-1, 4, 3, 1]
// i = 0
// i++
// i = 1
// nums = [-1, 1, 3, 4]
// i = 1
// nums = [1, -1, 3, 4]
// i = 1
// i++
// i = 2
// i++
// i = 3
// i++
const firstMissingPositive = (nums) => {
const swap = (i, j) => [nums[i], nums[j]] = [nums[j], nums[i]];
let i = 0;
while (i < nums.length) {
if (
nums[i] > 0 &&
nums[i] <= nums.length &&
nums[i] !== nums[nums[i] - 1]
) {
swap(nums[i] - 1, i);
} else {
i++;
}
}
for (let i = 0; i < nums.length; i++) {
if (nums[i] !== i + 1) return i + 1;
}
return nums.length + 1;
};