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个数,若都是连续的,最大的数是n,也就是说返回的值最大为n+1,遍历数组,如果当前的数num[i],
如果num[i]<=0或者num[i]超过了n,则第一个丢掉的整数必然在num[i]的前面,将num[i]和num[n-1]互换,n--;
如果1<=num[i]<=n,表明这个数可能是好的,将他放在正确的位置swap(num[i],num[num[i]-1])
如果num[i]==i+1,则表明该数字在正确的位置,i++
class Solution { public:int firstMissingPositive(int A[], int n) {int m = n;for(int i=0;i<m;i++){if(A[i] == i+1)continue;else{if(A[i] > m || A[i] == 0 || A[i] < 0 || A[i] <= i){if(i==m-1)return m;swap(A[i],A[m-1]);m--;i--;}else{if(A[i] == A[A[i]-1]){swap(A[i],A[m-1]);m--;i--;}else{swap(A[i],A[A[i]-1]);i--;}}}}return m+1;} };