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)的限制 。那么 其实 就是洗牌。。。。因为 数组是连续 的 那么肯定是 0 存1, 1的位置 存2 。。。。 i+1=A[i]。那么就按照 这个洗牌,当 A[A[i]-1]!=A[i], 那么 就 换下位置,然后 遍历一下 找不符合条件的就是第一个
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for (int i=0; i<n; i++){
int digit=A[i];
while(digit>0 && digit <=n && A[digit-1]!=digit){
swap(A[digit-1],A[i]);
digit=A[i];
}
}
for (int i=0; i<n; i++){
if (i+1!=A[i])
return i+1;
}
return n+1;
}
};