题目:
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.
思路: 主要的思想就是把对应的数放到对应的索引上,例如1放到A[1]上,这样只需要O(n)的遍历就能完成,然后用一个O(n)的遍历找第一个没有放到索引上的数返回。
代码:
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 5 for (int i=0; i<n; ++i) 6 { 7 if (A[i] > 0 && A[i] < n) 8 { 9 if (A[i]-1 != i && A[A[i]-1] != A[i]) 10 { 11 int temp = A[A[i]-1]; 12 A[A[i]-1] = A[i]; 13 A[i] = temp; 14 --i; 15 } 16 } 17 } 18 19 for (int j=0; j<n; ++j) 20 if (A[j]-1 != j) 21 return j+1; 22 23 return n+1; 24 } 25 };