【题目描述】Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run in O(n) time and uses constant space.
【解题思路】用数组本身来充当哈希表。稍微变通一下,在遍历数组的过程中把数字 i 放在A[i-1]的位置。最后如果A[k] != k+1就说明k+1这个数字没有出现过。由于数组的大小是n,因此如果原始数组中的数字是1,2…n,则最后应该返回n+1。
还需要注意的是if中判断条件:A[i] != A[A[i]-1];即如果某个位置A[i]已经放置了i+1或者数字A[i]即将要放入的位置(A[A[i]-1])原本就是A[i],则跳过。这样可以避免出现死循环(如数组[1,2]和[1,1])
【考查内容】数组
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i = 0;i < n;){
if(A[i]>0 && A[i]<=n && A[i] != A[A[i]-1]){ //在范围内,且不在正确的位置上要将A[i]调整到正确的位置
int index = A[i]; //不能简单的交换,否则A[A[i]-1]就不是原来的位置了!
int temp = index;
A[i] = A[index-1];
A[index-1] = temp;
}else //但是被换到A[i]的新值需要重新检测,所以当不满足条件的时候才增加i的值
++i;
}
for(int i = 0;i < n;i++)
if(A[i]!=i+1)
return i+1;
return n+1;
}
};