41. First Missing Positive(困难, 用到 counting sort 方法)

时间:2023-03-10 05:35:30
41. First Missing Positive(困难, 用到 counting sort 方法)

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.

若数组为[10,20,30], 则返回0+1 = 1, 因为 A[0]!=( 0 + 1 ).详细情况看下面.

人家解释:

http://www.cnblogs.com/ccsccs/articles/4216113.html

跟Counting sort一样,利用数组的index来作为数字本身的索引,把正数按照递增顺序依次放到数组中。即让A[0]=1, A[1]=2, A[2]=3, ... , 这样一来,最后如果哪个数组元素违反了A[i]=i+1即说明i+1就是我们要求的第一个缺失的正数。

\(O(n)\) time, \(O(1)\) extra space.

代码:

int firstMissingPositive(vector<int>& A) {
const int n = A.size();
// 难度是维护一个 A[i] = i + 1 的数组
// 我们只把小于等于数组长度的并且大于0的并且A[i] != i + 1的元素做调整
for (int i = 0; i < n; i++) {
if (A[i] <= n && A[i] > 0 && A[A[i] - 1] != A[i]) {
int temp = A[A[i] - 1];
A[A[i] - 1] = A[i];
A[i] = temp;
i--; // hard
}
} // 二次扫描,找出A[i] != i + 1的元素
for (int i = 0; i < n; i++) {
if (A[i] != i + 1)
return i + 1;
}
return n + 1;
}