LeetCode 41.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开始算起。后来纠正了之后其实题目就不难了。每找到一个数就把它换到正确的位置上,直到换不下去为止。整个排序结束后再进行一次遍历,从0开始找第一个丢失的正数即可。

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


你可能感兴趣的:(array)