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) {
bucket_sort(A, n);
for (int i = 0; i < n; i++) {
if (A[i] != i+1) {
return i+1;
}
}
return n+1;
}
void bucket_sort(int A[], int n) {
for (int i = 0; i < n; i++) {
while (A[i] != i+1) {
if (A[i] <= 0 || A[i] > n || A[i] == A[A[i]-1]) {
break;
}
swap(A[i], A[A[i]-1]);
}
}
}
};
本文介绍了一种在未排序整数数组中查找第一个缺失正整数的算法,该算法能在O(n)时间内运行并使用常数级空间复杂度。通过桶排序思想,将每个元素放到其应该所在的位置上,从而快速定位缺失的数值。
159

被折叠的 条评论
为什么被折叠?



