# [leetcode-41]First Missing Positive(java)

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.

这道题刚开始怎么也没看懂啥意思，实际上是给了一个数组，然后看从1开始，看看缺少了哪个整数，缺少的第一个就是要返回的值。难点在于要求常数的空间使用，下面给出两种方法，第一种严格意义上讲是错误的，因为它的空间复杂度为O(n)但是很简洁。使用的是hashset。



    public int firstMissingPositive(int[] nums) {
HashSet<Integer> set = new HashSet<Integer>();
int length = nums.length;
if(length<=0)
return 1;

for(int i = 0;i<length;i++){
}

int index = 1;
while(set.contains(index++));
return index-1;
}

public int firstMissingPositive(int[] nums){
int length = nums.length;
if(length<=0)
return 1;
int i;
int index,nextIndex;
int current,next;
for(i = 0;i<length;i++)
if(nums[i]<0)
nums[i] = 0;
for(i = 0;i<length;i++){
current = nums[i];
index = current%length;
if(i == index)
continue;
next = nums[index];
nextIndex = next%length;

while(nextIndex!=index){
nums[index] = current;
current = next;
index = nextIndex;
next = nums[index];
nextIndex = next%length;
}
if(current<nums[index]&&current>0)
nums[index] = current;
}
i = 1;
while(nums[i%length]==i)i++;
return i;
}

int firstMissingPositive(int* nums, int numsSize) {
int length = numsSize;
if(length<=0)
return 1;
int i;
int index,nextIndex;
int current,next;
for(i = 0;i<length;i++)
if(nums[i]<0)
nums[i] = 0;
for(i = 0;i<length;i++){
current = nums[i];
index = current%length;
if(i == index)
continue;
next = nums[index];
nextIndex = next%length;

while(nextIndex!=index){
nums[index] = current;
current = next;
index = nextIndex;
next = nums[index];
nextIndex = next%length;
}
if(current<nums[index]&&current>0)
nums[index] = current;
}
i = 1;
while(nums[i%length]==i)i++;
return i;
}

• 本文已收录于以下专栏：

## DAY28：leetcode #41 First Missing Positive

Given an unsorted integer array, find the first missing positive integer. For example, Given [1,...

## leetcode 41. First Missing Positive

1.题目 Given a collection of candidat...

## Leetcode41. First Missing Positive

Leetcode First Missing Positive

## [leetcode]41. First Missing Positive,C++/python实现，hard难度

[leetcode]41. First Missing Positive,C++/python实现，hard难度

## [LeetCode - 桶排序] 41. First Missing Positive

1 问题 Given an unsorted integer array, find the first missing positive integer. For example, ...

## leetcode 41. First Missing Positive

import java.util.Arrays; //Given an unsorted integer array, find the first missing positive integer...

举报原因： 您举报文章：深度学习：神经网络中的前向传播和反向传播算法推导 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)