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.
先排序,再检查,交换
class Solution {
public:
int firstMissingPositive(int A[], int n) {
sort(A, A+n);
int res = 0;
int i = 0;
while (i<n && A[i]<=0) i++;
for (; i < n; i++)
{//注意:一看到序列就应该马上反应问题:是否有重复元素???
if (i>0 && A[i] == A[i-1]) continue;
if (A[i] - res != 1) return res+1;
else res = A[i];
}
return res+1;
}
};
或者,先交换排序,后检查
class Solution {
public:
int firstMissingPositive(int A[], int n) {
int i = 0;
while (i < n)
{
if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i])
swap(A[i], A[A[i]-1]);
else
i++;
}
for (i = 0; i < n; ++i)
if (A[i] != (i+1))
return i+1;
return n+1;
}
};