欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

First Missing Positive

程序员文章站 2022-05-24 12:48:42
...
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;
    }
}
相关标签: 桶排序