First Missing PositiveMar 8 '125401 / 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;
}
};

本文介绍了一种在未排序整数数组中查找第一个缺失正整数的方法,并提供了一个运行时间为O(n)且使用常数空间的算法实现。示例包括给定数组[1,2,0]返回3及[3,4,-1,1]返回2。
270

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



