[LeetCode(Q41)] First Missing Positive (乱序数组中寻找第一个未出现的正整数)

Q:

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.

寻找数组中第一个未出现的正整数,题目本身比较常见,关键在于题目要求只能使用常数额外空间。

A:

虽然不能再另外开辟非常数级的额外空间,但是可以在输入数组上就地进行swap操作。

思路:交换数组元素,使得数组中第i位存放数值(i+1)。最后遍历数组,寻找第一个不符合此要求的元素,返回其下标。整个过程需要遍历两次数组,复杂度为O(n)

下图以题目中给出的第二个例子为例,讲解操作过程。

最后,具体实现如下:

 1 class Solution {
 2 public:
 3     int firstMissingPositive(int A[], int n) {
 4         int i = 0;
 5         while (i < n)
 6         {
 7             if (A[i] != (i+1) && A[i] >= 1 && A[i] <= n && A[A[i]-1] != A[i])
 8                 swap(A[i], A[A[i]-1]);
 9             else
10                 i++;
11         }
12         for (i = 0; i < n; ++i)
13             if (A[i] != (i+1))
14                 return i+1;
15         return n+1;
16     }
17 };

 

关于LeetCode的其他题目,可以参考我的GitHub

原创文章,转载请注明出处:http://www.cnblogs.com/AnnieKim/

posted @ 2013-04-21 22:04  AnnieKim  阅读(19122)  评论(6编辑  收藏  举报