leetcode no 41 first missing positive

1. 题目

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.

2. 思路

先将数字移到合适的位置(比如 1 移到下标为 0 的位置,2 移到下标为 1 的位置)再进行检查。符合O(n)的时间复杂度。

public class  {
    public int firstMissingPositive(int[] nums) {
        int len = nums.length;
        for(int i=0; i<len; i++){
            while(nums[i] > 0 && nums[i] <= len && nums[i] != nums[nums[i]-1]){
                int temp = nums[i];
                nums[i] = nums[temp-1];
                nums[temp-1] = temp;
            }
        }
        for(int i=0; i<len; i++){
            if(nums[i] != i+1){
            return i+1;
            }
        }
        return len+1;        
    }
}