题目
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0]
Output: 3
Example 2:
Input: [3,4,-1,1]
Output: 2
Example 3:
Input: [7,8,9,11,12]
Output: 1
Follow up:
Your algorithm should run in O(n) time and uses constant extra space.
思路
题目要求不用额外的空间,所以只能在原数组上进行操作,思路是遍历第一轮将1放到nums[0]的位置,i放到nums[i-1]的位置,第二轮遍历的时候找到最早不满足nums[i] = i + 1的角标。
需要注意的地方:
- 如例2例3中有负数和超过nums[i]的数,此时没有它们对应的位置,保持不动,或者被别的交换
- 如果有重复的数字,第一次遇到这个数时把它放到了nums[i-1],第二次遇到也不用再交换两个一样的数了
- 交换完后要将index–,如例三中,首先交换-1和3,变成了[-1,4,3,1],如果我们直接将index增大,会发现-1这个数其实从头到尾都没有被判断过,虽然这里暂时还没有结果差异(-1本来也不做操作);下一步交换4和1,变成[-1,1,3,4],如果不重新判断1的话这就是最终结果,1不会再被放到正确的位置,所以要回退。
代码
class Solution {
public int firstMissingPositive(int[] nums) {
int temp;
for (int i = 0; i < nums.length; i++) {
if (0 < nums[i] && nums[i] <= nums.length && nums[nums[i] - 1] != nums[i]) {
temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
i--; // 不能省略
}
}
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
return i + 1;
}
}
return nums.length + 1;
}
}