leetcode:41. First Missing Positive (Java)

Posted boy_nihao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    

以上是关于leetcode:41. First Missing Positive (Java)的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 41. First Missing Positive

LeetCode OJ 41First Missing Positive

[array] leetcode - 41. First Missing Positive - Hard

[leetcode-41-First Missing Positive]

Leetcode 41: First Missing Positive

LeetCode41 First Missing Positive