【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.

找到第一个没有出现的正整数

 

思路:

http://tech-wonderland.net/blog/leetcode-first-missing-positive.html

就是把出现的正整数a都放在a-1的位置,然后从头开始历遍,发现A[i] != i + 1的情况就是所要的结果

 

代码:

class Solution {

public:

    int firstMissingPositive(int A[], int n) {

        int i = 0, j;

        while (i < n)

        {

            if (A[i] != i + 1 && A[i] > 0 && A[i] <= n && A[i] != A[A[i]-1])

                swap(A[i], A[A[i]-1]);

            else i++;

        }



        for (j = 0; j < n; j++)

            if (A[j] != j + 1)

                return j + 1;

        return n + 1;

    }

};

 

你可能感兴趣的:(LeetCode)