LeetCode 41:First Missing Positive Number

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.

思路:用桶排序。重复使用所给的空间。

public class Solution {
    public int firstMissingPositive(int[] nums) {
        for(int i=0;i){
            if(nums[i]>0&&nums[i]]){
                int temp=nums[nums[i]-1];
                nums[nums[i]-1]=nums[i];
                nums[i]=temp;
                i--;
            }
            
        }
        for(int j=0;j){
            if(nums[j]!=j+1)
            return j+1;
        }
        return nums.length+1;
    }
}
View Code

 

转载于:https://www.cnblogs.com/gonewithgt/p/4566114.html

你可能感兴趣的:(LeetCode 41:First Missing Positive Number)