问题描述:
Given an unsorted integerarray, 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.
问题分析:
由于要求空间复杂度为O(1),而数组中的元素已经被限定到1—N,故可以想到使用原数组来作为存储记录的空间,将1保存到nums[0],i保存到nums[i - 1];
在第一次遍历的时候,通过交换将i保存到nums[i - 1],
第二次遍历的时候,只需要找到第一个不连续的正整数值,即为所丢失的结果。
代码:
public class Solution {
public int firstMissingPositive(int[] nums) {
for (int i = 0; i < nums.length; i++) {
// 以nums来记录出现的数字,由于只考虑正数,则只用考虑1~length,其它的不用考虑
// 将范围在number = 1~length的数字挪到对应的nums[number-1]即可;
// 最后遍历修改后的数组,即可找到第一个丢失位置
// 注意还要对交换过后的i位置的元素进行判断,直至i满足条件
while (nums[i] > 0 && nums[i] <=nums.length && nums[nums[i] - 1] != nums[i]) {
// 交换对应值
swap(nums, i, nums[i] - 1);
}
}
// 再一次遍历,找到遗失值
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1)
return (i + 1);
}
return nums.length + 1;
}
// 交换数组中的两个位置
private voidswap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
运行结果: