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.
这道题蛮难啊,看起来比较简单,但是到下手的时候就不会了。
这道题的思路是以前没有接触过的,由于要求O(n)的时间复杂度,只能常数次遍历数组,所以就是将每个数n放到数组中序号为(n-1)的位置上,其中负数和大于数组长度的数不用管,没有他们的位置。重复的数也只放一次就好了,这样再遍历一遍之后,再从头开始遍历数组,当哪个位置上的数不是希望的,则该位置希望的数就是缺少的第一个正整数。如果全都是希望的数,那么所缺的就是数组长度加一的那个数。代码如下:
public class Solution {
public int firstMissingPositive(int[] nums) {
int len = nums.length;
for(int i = 0; i < len;){
if(nums[i] != i+1 && nums[i] > 0 && nums[i] <= len && nums[i] != nums[nums[i]-1] ){
swap(i,nums[i]-1,nums);
}
else{
i++;
}
}
for(int i = 1; i <= len; i++){
if(nums[i-1] != i){
return i;
}
}
return len+1;
}
private void swap(int i, int j, int[] nums) {
// TODO Auto-generated method stub
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}