leetcode第40题--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.

给定一个没有排好序的数组。找出其中第一个消逝的正整数。例如 [1,2,5,4]那就是缺3.

思路:利用counting sort的想法。遍历一次,如果当前的数超出了 1 到 n-1的范围,跳过。如果是1到n-1但是,A[i]不等于i+1,并且在 A[i] - 1 的位置的数不满足 A[A[i]-1]+1的要求,那就将两个位置的数置换。同时,还要在当前位置判断换过来的数是否满足上述要求。这个哥们的图很好理解。

class Solution {
public:
    void swap40(int A[], int i, int j) // 其实std有自带的函数swap(A[i], A[j])
    {
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
        return;
    }
    int firstMissingPositive(int A[], int n) 
    {
        if (n <= 0 )
            return 1;
        for (int i = 0; i < n; ++i)
        {
            if (A[i] > 0 && (A[i] - 1 < n) && A[i] != i + 1 && A[i] != A[A[i] - 1])
                {swap(A, i, A[i] - 1);i--;} // i--是为了和之后的++i持平,因为交换的条件满足的话,交换过来的数还要再判断
        }
        for (int i = 0; i < n; ++i)
        {
            if (A[i] != i + 1)
                return i + 1;
        }
        return n + 1;
    }
};

 

posted on 2014-10-26 22:05  higerzhang  阅读(194)  评论(0编辑  收藏  举报