|
1 | 1 | /** |
2 | | - * https://leetcode.com/problems/first-missing-positive/ |
3 | | - * Time O(n) | Space O(1) |
| 2 | + * Cyclic Sort |
| 3 | + * Time O(N) | Space O(1) |
| 4 | + * https://leetcode.com/problems/first-missing-positive |
4 | 5 | * @param {number[]} nums |
5 | 6 | * @return {number} |
6 | 7 | */ |
7 | | -var firstMissingPositive = function(nums) { |
8 | | - //-1 1 3 4 |
9 | | - const swap = (a, b) => { |
10 | | - const temp = nums[a]; |
11 | | - nums[a] = nums[b]; |
12 | | - nums[b] = temp; |
13 | | - } |
14 | | - |
15 | | - // swap positions |
16 | | - for (let i = 0; i < nums.length; i++) { |
17 | | - const el = nums[i]; |
18 | | - const chair = el - 1; |
19 | | - if (el >= 1 && el <= nums.length + 1 && nums[chair] !== el) { |
20 | | - swap(chair, i); |
21 | | - i--; // this decrement is important // check this input [3,4,-1,1] |
22 | | - } |
23 | | - } |
24 | | - |
25 | | - for (let i = 0; i < nums.length; i++) { |
26 | | - if (nums[i] !== i + 1) return i + 1; |
27 | | - } |
| 8 | +var firstMissingPositive = (nums) => { |
| 9 | + cyclicSort(nums); |
28 | 10 |
|
29 | | - return nums.length + 1; |
| 11 | + return search(nums); |
30 | 12 | }; |
31 | 13 |
|
32 | | -/** |
33 | | - * Time O(n) | Space O(n) |
34 | | - * @param {number[]} nums |
35 | | - * @return {number} |
36 | | - */ |
37 | | -var firstMissingPositive1 = function(nums) { |
38 | | - const numberSet = new Set(nums); |
39 | | - |
40 | | - let i = 1; |
41 | | - while (numberSet.has(i)) { |
42 | | - i++; |
| 14 | +const cyclicSort = (nums, index = 0) => { |
| 15 | + while (index < nums.length) { |
| 16 | + const num = nums[index]; |
| 17 | + const indexKey = (num - 1); |
| 18 | + const indexNum = nums[indexKey]; |
| 19 | + |
| 20 | + if (canSwap(nums, num, indexNum)) { |
| 21 | + swap(nums, index, indexKey); |
| 22 | + continue; |
43 | 23 | } |
44 | | - |
45 | | - return i; |
46 | | -}; |
| 24 | + |
| 25 | + index += 1; |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +const search = (nums, index = 0) => { |
| 30 | + while (index < nums.length) { |
| 31 | + const num = nums[index]; |
| 32 | + const indexKey = (index + 1); |
| 33 | + |
| 34 | + if (!isEqual(num, indexKey)) return indexKey; |
| 35 | + |
| 36 | + index += 1; |
| 37 | + } |
| 38 | + |
| 39 | + return (nums.length + 1); |
| 40 | +} |
| 41 | + |
| 42 | +const canSwap = (nums, num, indexNum) => |
| 43 | + isPositive(num) && |
| 44 | + isInBound(num, nums) && |
| 45 | + !isEqual(num, indexNum); |
| 46 | + |
| 47 | +const swap = (nums, index, indexKey) => |
| 48 | + [nums[index], nums[indexKey]] = [nums[indexKey], nums[index]]; |
| 49 | + |
| 50 | +const isPositive = (num) => (0 < num); |
| 51 | + |
| 52 | +const isInBound = (num, nums) => (num <= nums.length); |
| 53 | + |
| 54 | +const isEqual = (num, indexNum) => (num === indexNum); |
| 55 | + |
| 56 | + |
0 commit comments