[LeetCode] 41. 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.



Solution

The solution can look like this, whenever the nums[i] != i+1, we swap the number with nums[nums[i]-1] to make sure that every number in the array is in the correct order.

Once the array is sorted, we can check whether the nums[i] == i+1, and the first place that does not satisfy this requirement should be the output value.


However, what if the value of certain numbers in the array is way too big, then the array may not have enough space to store all the value. For example,

nums[] = {2,3,5,999998};

We can solve this problem by ignoring numbers that is bigger than the size of the array.

But another problem also rises. How can we make sure that the numbers we ignored have no influence on the output?

Well, as the only scenario that this large number may influence the output is that all the numbers before this large number must be present, for example

nums[] = {2,3,4,5,...,999997,999998};

and in this case, the array itself would be equally large, and have no problem containing all numbers.


The code is shown as below.
Java

public class Solution {
    public int firstMissingPositive(int[] nums) {
        
        int i=0;
        
        while(i nums.length || nums[i] == i+1){
                i++;
                continue;
            }
            
            if(nums[nums[i]-1] != nums[i]) 
                swap(nums, i, nums[i]-1);
            else i++;
        }
        
        i=0;
        while(i


你可能感兴趣的:([LeetCode] 41. First Missing Positive)