-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0041-first-missing-positive.js
56 lines (41 loc) · 1.12 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
/**
* Cyclic Sort
* Time O(N) | Space O(1)
* https://leetcode.com/problems/first-missing-positive
* @param {number[]} nums
* @return {number}
*/
var firstMissingPositive = (nums) => {
cyclicSort(nums);
return search(nums);
};
const cyclicSort = (nums, index = 0) => {
while (index < nums.length) {
const num = nums[index];
const indexKey = (num - 1);
const indexNum = nums[indexKey];
if (canSwap(nums, num, indexNum)) {
swap(nums, index, indexKey);
continue;
}
index += 1;
}
}
const search = (nums, index = 0) => {
while (index < nums.length) {
const num = nums[index];
const indexKey = (index + 1);
if (!isEqual(num, indexKey)) return indexKey;
index += 1;
}
return (nums.length + 1);
}
const canSwap = (nums, num, indexNum) =>
isPositive(num) &&
isInBound(num, nums) &&
!isEqual(num, indexNum);
const swap = (nums, index, indexKey) =>
[nums[index], nums[indexKey]] = [nums[indexKey], nums[index]];
const isPositive = (num) => (0 < num);
const isInBound = (num, nums) => (num <= nums.length);
const isEqual = (num, indexNum) => (num === indexNum);