原题:
解决方法:
代码:
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.
解决方法:
由于时间复杂度和空间复杂度的要求,这道题需要用到一些巧妙的方法。
首先需要找到的是结果肯定是在1~N+1之间,其中N是数组的长度。
利用结果的有序性,我们可以将符合要求的数放在相对应的数组里面,例如1放在0,2放在1,......, N放在N-1。
当放好以后,再次从前往后扫描,找到第一个序号与结果不相匹配的值就是我们所求的结果。
边界条件是前N个数数都已经放好了,我们需要插入N+1这个数。
代码:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size();
for(int i = 0; i < n; i++){
if (nums[i] == i + 1){
continue;
}
int index = nums[i];
while(index > 0 && index <= n && nums[index -1] != index)
swap(index, nums[index -1]);
}
for(int i = 0; i < n; i++){
if (nums[i] != i + 1)
return i + 1;
}
return n + 1;
}