[LeetCode] First Missing Positive

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 };
posted @ 2012-10-31 11:34  chkkch  阅读(2545)  评论(2编辑  收藏  举报