|
| 1 | +/** |
| 2 | + * Cyclic Sort |
| 3 | + * Time O(N) | Space O(1) |
| 4 | + * https://leetcode.com/problems/first-missing-positive |
| 5 | + * @param {number[]} nums |
| 6 | + * @return {number} |
| 7 | + */ |
| 8 | +var firstMissingPositive = (nums) => { |
| 9 | + cyclicSort(nums); |
| 10 | + |
| 11 | + return search(nums); |
| 12 | +}; |
| 13 | + |
| 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; |
| 23 | + } |
| 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