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.

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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章