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.
Subscribe to see which companies asked this questio
public class Solution {
public int firstMissingPositive(int[] nums) {int ret = 1;
int length = nums.length;
boolean findMissFlag = false;
if(nums == null || length == 0)
{
return 1;
}
Set<Integer> set = new HashSet<Integer>();
int max = 0;
for(int i = 0; i < length;i++)
{
if(nums[i] > 0)
{
set.add(nums[i]);
if(nums[i] > max)
{
max = nums[i];
}
}
}
for(int j = 1; j <= max;j++)
{
if(set.contains(j) == false)
{
ret = j;
findMissFlag = true;
break;
}
}
if(findMissFlag == false)
{
ret = max + 1;
}
return ret;
}
}