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.
思路:用swap来保持constant space,思路就是让数字保存在它应该在的地方,也就是nums[i] - 1的index上,比如:1就是在0的位置上,2在1的位置上,当前i的数字,如果不是i+1,就继续把当前的数字放在它该有的位置上,换过来的数字如果不是,继续换,最后再扫描一遍,如果nums[i] 不是i+1,就返回i+1,如果都是就返回nums.length + 1;
注意while循环内,不能是负数,而且不能越界,也就是999,[1, 999] 也不行;到达了最后,代表前面的全部安排正确,那么就是length + 1;
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i = 0; i < n; i++) {
while(0 <= nums[i] - 1 && nums[i] - 1 <= n - 1 && nums[i] != nums[nums[i] - 1]) {
swap(nums, i, nums[i] - 1);
}
}
for(int i = 0; i < n; i++) {
if(nums[i] != i + 1) {
return i + 1;
}
}
return n + 1;
}
private void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}