一、题目叙述:
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 question.
二、解题思路:
理解题意最重要了,所有情况下都是丢失的最小正数。
(1)考虑三种情况:1、数组中没有正数,此时返回1;2、数组中最小的正数大于1,此时返回1;3、数组中有正数且最小正数为1,此时需要考虑以下步骤:
(2)开辟大小为size + 1的布尔型数组note,用于记录每个数字是否出现过,出现了标记为true(此处注意若出现的正数超过了数组大小,则不考虑因为没意义,前面必然有某个更小的正数缺失了);
(3)遍历数组,发现false,返回i值;若没有false,亦返回i值。
三、源码:
public class Solution
{
public int firstMissingPositive(int[] nums)
{
// int result = 1;
int i = 0;
int min = Integer.MAX_VALUE;
int size = nums.length;
boolean[] note = new boolean[size+1];
note[0] = true;
// if (size == 0) return 1;
for (i = 0; i < size; i++)
{
if (nums[i] > 0 && nums[i] < min) min = nums[i];
}
if (min == Integer.MAX_VALUE || min > 1) return 1;
for (i = 0; i < size; i ++)
{
if (nums[i] > 0 && nums[i] < 1 + size) note[nums[i]] = true;
}
for (i = 0; i < size + 1; i++)
{
if (note[i] == false)
break;
}
// if (i == size + 1) result = i;
return i;
}
public static void main(String args[])
{
// int[] digits = {0};
Solution solution = new Solution();
int[] abc = {2};
// int[] b = {2,3,4};
// for(int i = 0; i < abc.length; i ++)
System.out.print(solution.firstMissingPositive(abc));
}
}