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.
參考這里的解答:http://dl.dropbox.com/u/19732851/LeetCode/FirstMissingPositive.html
主要的思想就是把對應的數放到對應的索引上,例如1放到A[1]上,這樣只需要O(n)的遍歷就能完成,然后用一個O(n)的遍歷找第一個沒有放到索引上的數返回。
最后就是可能A[0] == n,這時就要有個特殊情況的處理。
1 class Solution { 2 public: 3 int firstMissingPositive(int A[], int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int i = 0; 7 while(i < n) 8 { 9 if (A[i] == i) 10 i++; 11 else 12 { 13 if (0 <= A[i] && A[i] < n && A[A[i]] != A[i]) 14 { 15 int t = A[i]; 16 A[i] = A[A[i]]; 17 A[t] = t; 18 continue; 19 } 20 else 21 i++; 22 } 23 } 24 25 for(int i = 1; i < n; i++) 26 if (A[i] != i) 27 return i; 28 29 return A[0] == n ? n + 1 : n; 30 } 31 };
