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.

用到了桶排序,我们让第i个位置放值为i + 1的元素。当nums[i]不等于i + 1时,就让nums[nums[i] - 1]] = nums[i], 这样nums[nums[i] - 1]的位置肯定符合nums[i] = i + 1。然后在遍历一遍数组,如果遇到nums[i] 不等于 i + 1时就返回i+ 1,这个数字就是第一个missing的正数。代码如下:
public class Solution {
    public int firstMissingPositive(int[] nums) {
        if(nums == null) return 0;
        for(int i = 0; i < nums.length; i++) {
            while(nums[i] - 1 != i) {
                if(nums[i] <= 0 || nums[i] >= nums.length || nums[nums[i] - 1] == nums[i]) break;
                int tem = nums[nums[i] - 1];
                nums[nums[i] - 1] = nums[i];
                nums[i] = tem;
            }
        }
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != i + 1) return i + 1;
        }
        return nums.length + 1;
    }
}

你可能感兴趣的:(桶排序)