leetcode:41. First Missing Positive (Java)

转载请注明出处:z_zhaojun的博客
原文地址
题目地址
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.

代码实现(Java):

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

你可能感兴趣的:(java,LeetCode,博客)