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.
方法:每次判断a[i]==i。
if true,i++
else 将交换a[i]和a[a[i]]。让a[a[i]] = a[i];
class Solution {
public:
void swap(int& a, int& b) {
int t = a;
a = b;
b = t;
}
int firstMissingPositive(int A[], int n) {
for (int i = 0; i < n; i++) A[i]--;
int*a = A;
for (int i = 0; i < n; i++) {
while (a[i] != i && a[i] >= 0 && a[i] < n) {
if (a[a[i]] == a[i]) break;
swap(a[i], a[a[i]]);
}
}
for (int i = 0; i < n; i++) {
if (a[i] != i) return i+1;
}
return n+1;
}
};