[LeetCode][JavaScript]First Missing Positive

First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

https://leetcode.com/problems/first-missing-positive/


要求线性的时间复杂度,就不能排序了,常数的空间复杂度,不能用哈希表。

要找出第一个未出现的数字。

给定的数组大小为n,结果不可能超过n。

遍历数组,把小于等于n的正数放到数组中下标为n-1的位置。

这边需要递归,因为被交换的数也可能也需要放到指定的位置。

最后遍历交换过顺序的数组,如果某个位置(nums[i])的值不等于i+1,i+1就是结果。

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var firstMissingPositive = function(nums) {
 6     for(var i = 0; i < nums.length; i++){
 7         move(i);
 8     }
 9     for(i = 0; i < nums.length; i++){
10         if(nums[i] !== i + 1){
11             return i + 1;
12         }
13     }
14     return nums[i - 1] ? nums[i - 1] + 1 : 1;
15 
16     function move(i){
17         var tmp;
18         if(nums[i] > 0 && nums[i] <= nums.length && nums[nums[i] - 1] !== nums[i]){
19             tmp = nums[nums[i] - 1];
20             nums[nums[i] - 1] = nums[i];
21             nums[i] = tmp;
22             move(i);
23         }
24     }
25 };
原文地址:https://www.cnblogs.com/Liok3187/p/4695445.html