First Missing Positive[No]

 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[0] = 1 A[1] = 2....A[i] = i+1; 正确的存储.此题目没有好好解答出来。再思考。

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i = 0;
        for(i = 0; i < n;){
            if (A[i] == i + 1){
                i++;
            }else if (A[i] < i+1 || A[i] -1 > n || A[A[i] -1] == A[i]){
                A[i] = A[--n];                
            }else{
                int  t = A[i];
                A[i] = A[t - 1];
                A[t - 1] = t;
            }
        }
        return n + 1;
    }
};

 

posted @ 2013-07-16 23:23  一只会思考的猪  阅读(175)  评论(0)    收藏  举报