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.
这道题其实用到了动态规划的思想,因为有n个数,那么在遍历数组的是会根据当前元素的值(如果大于0, 小于n)跟对应元素的值做一下交换,这样在第二次遍历一遍数组的时候就可以根据数据当前元素的值跟下标i的关系找出缺失的第一个整数。
- 一旦想明白了,写代码还是比较容易的。C++ AC代码如下:
class Solution {
public:
int firstMissingPositive(int A[], int n) {
int i = 0;
while (i < n)
{
if (A[i] != (i + 1) && A[i] >= 1 && A[i] <= n && A[A[i] - 1] != A[i])
swap(A[i], A[A[i] - 1]);
else
i++;
}
for (i = 0; i < n; ++i)
if (A[i] != (i + 1))
return i + 1;
return n + 1;
}
};