參考鏈接
http://blog.csdn.net/doc_sgl/article/details/12321271題目描述
First Missing Positive
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.
題目分析
以[3,4,-1,1]爲例:
總結
代碼示例
class Solution {
public:
int firstMissingPositive(int A[], int n) {
////////////////////////////// for(int i = 0;i<n;i++)
int i = 0;
while(i<n)
{
if(A[i] != i+1 && A[i]>0 && A[i]-1<n && A[i] != A[A[i]-1])
swap(A[i],A[A[i]-1]);
else
i++;
}
for(int i = 0;i<n;i++)
if(A[i] != i+1) return i+1;
return n+1;
}
};