First Missing Positive
Mar 8 '12
5401 / 16835
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) { int *a = A, tmp; for (int i = 0; i < n; i++) { if (a[i] == i+1) continue; while (a[i] != i+1) { if (a[i] > n || a[i] <= 0) break; if (a[a[i]-1] == a[i]) break; swap(a[i], a[a[i]-1]); } } for (int i = 0; i < n; ++i) { if (a[i] != i+1) return i+1; } return n+1; } };