题目
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.
从头向尾扫描,
如果数i在[1,n],且数i和编号为i-1的数不等,则交换两者。
处理一遍后,所有[1,n]的数在正确的位置上都有出现,
如果相应位置i-1上的数不是i,则数i是缺的,从头向后扫一次即可。
代码:
class Solution { public: int firstMissingPositive(int A[], int n) { int i=0; while(i<n) //交换元素到合适的位置 { if(A[i]>0&&A[i]<=n&&A[i]!=i+1&&A[i]!=A[A[i]-1]) 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; } };