一.问题描述
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)。所以我一直在想怎么在不同下标元素的遍历之间建立联系,想来想去也没有太好的办法。
网上的思路比较精彩,从结果出发,要求数组第i个位置放置i+1这个数,这样只需要对原数组进行遍历+swap即可。这题的边界条件也比较难,需要仔细思考才能加上swap的两个元素相等,导致循环出不去的问题。最后测试通过的程序如下:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int len = nums.size();
int idx = 0;
if(len==0)
return 1;
while(idx<len){
int tmp = nums[idx];
if(tmp>0&&tmp<len+1&&tmp!=idx+1&&tmp!=nums[tmp-1])
swap(nums,idx,tmp-1);
else
idx++;
}
for(int i=0;i<len;i++){
if(nums[i]!=i+1 )
return i+1;
}
return len+1;
}
void swap(vector<int>& nums,int a, int b)
{
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
};