1.题目
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
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.
这题题目可能有人会误解,其实是找0-正无穷间第一个消失的正整数。
比如数组[4,6,7],应该返回1,而不是返回5.
2.思路
此题难在要用O(n)时间复杂度和O(1)的空间复杂度求解问题,不然排序很容易解决。经过一番查阅,发现最经典的思路如下:
当我们遍历数组的时候,如果我们发现A[i] != i,那么我们就swap(A[A[i]], A[i]),让A[i]放在正确的位置上。而对于交换之后的A[i],我们继续做这个操作,直至交换没有意义为止。没有意义表示当前数不是正数,或超过数组长度,或与A[A[i]]相等。我们不关心这些数被排在什么位置。此外还要考虑如果整个数组都是连续的正数,比如A[] = {1,2},经过我们上面的排序之后会变成{2, 1},因为A[1] == 1(从1开始对比),而A[2]超出范围,所以函数会认为2之前的都出现过了而2没有出现过,返回2。为了防止把正确的数"挤"出数组,我们让A[A[i]-1]与A[i]交换,然后比较i+1和A[i]。
摘自:点击打开链接
所以,代码如下:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int n = nums.size(),i;
for ( i=0; i<n; ){
if (nums[i] <= 0 || nums[i] > n || nums[i] == i+1 || nums[i] == nums[nums[i]-1]) i++; // 无效交换或位置正确
else swap(nums[i], nums[nums[i]-1]); // 交换到正确的位置上
}
for (i = 0; i < n; i++) if (nums[i] != i+1) break; // 寻找第一个丢失的正数
return i+1;
}
};