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.

寻找第一个miss的正数,把数组排序就ok了,因为空间复杂度需要为1,所以在原数组上对元素交换就行。

如果A[i] != i + 1,那么就把第i 个数与第 A[i] - 1 个数进行交换,直到无法继续交换。

由于每个数交换一次就到了正确的位置,而处于正确位置的数(以及无法交换的数)并不需要交换,所以复杂度为O(n)

AC代码:

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

 

posted on 2014-12-10 15:33  远近闻名的学渣  阅读(114)  评论(0)    收藏  举报

导航