给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
说明:
你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
思路:把所有的正数都放回他们对应的位置,比如1放到第一个位置(索引为0),2放到第二个位置(索引为1)。
然后遍历数组,看看先缺少哪个数字。
代码:
public int firstMissingPositive(int[] nums) {
int i = 0;
while(i < nums.length) {
if(nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1]) {
int temp = nums[i];
nums[i] = nums[temp - 1];
nums[temp - 1] = temp;
}else
i ++;
}
for(i = 0; i < nums.length; i ++) {
if(nums[i] != i + 1)
return i + 1;
}
return nums.length + 1;
}