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.

思路:需找数组中第一个未出现的正整数,要求时间复杂度为O(n),空间复杂度为常数,则我们可以在原有数组上做交换。就是让数组中的第i位对应i+1的数值,然后遍历数组找到缺失的数值。

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        for(int i=0;i<n;i++)
        {
            int data=A[i];
            while(data>=1&&data<=n&&A[data-1]!=data)
            {
                swap(A[data-1],data);
            }
        }
        for(int i=0;i<n;i++)
        {
            if(A[i]!=i+1)
                return i+1;
        }
        return n+1;
    }
};

 

posted @ 2014-05-23 11:15  Awy  阅读(104)  评论(0编辑  收藏  举报