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
Note:
Your algorithm should run in O(n) time and uses constant extra space.
比较有趣的是题干要求时间复杂度O(n)并且只能使用O(1)的额外空间,这就意味着不能排序,不能用hashmap,也不能新建一张表来记录有过的点。
想了十分钟没想到办法,看了评论,才醒悟过来可以使用原数组的空间来作记录啊!
具体来说,遍历数组,一旦遇到大于0并且小于数组上限的值,就放到数组对应的位置当中去。在放到对应位置的同时,当然也要妥善处理好目标位置上的数字。并且在遍历过程中不能重复访问那些已经被换过,处在正确的位置上的数字,以保证即使有双层循环也一定是O(n)的时间。
下面是代码:
class Solution {
public int firstMissingPositive(int[] nums) {
int p = 0;
for(p=0;p<nums.length;p++)
{
int temp =nums[p];
while(temp>0 && temp<=nums.length && nums[temp-1]!=temp)
{
int temp2 = nums[temp-1];
nums[temp-1] = temp;
temp = temp2;
}
}
for(p=0;p<nums.length;p++)
{
if(nums[p]!=p+1)
return p+1;
}
return nums.length+1;
}
}