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) {
for(int ii = 0; ii < n; ii ++) {
// Use while to make number on position ii to be ii + 1 or invalid number.
// And swap may be called more than one time.
while(A[ii] != ii + 1 && A[ii] >= 1 && A[ii] <= n && A[ii] != A[A[ii] - 1])
swap(A[ii], A[A[ii] - 1]);
}
int ii = 0;
for(; ii < n; ii ++) {
if(A[ii] != ii + 1) return ii + 1;
}
return n + 1;
}
};
此算法在给定无序整数数组中找到首个缺失的正整数,时间复杂度为O(n),且使用常量空间。通过迭代数组并交换元素到其正确位置来实现。
1455

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



