First Missing Positive (寻找第一个丢失的正数)【leetcode】

题目:

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.

贪心的策略,O(n)的循环把数字放到其对应的位置,即满足A[i]=i+1,就能保证每次交换就是有意义的。

如果当前位置已经存在正确的值,就不交换,否则会死循环。

最后在扫描一遍,如果当前位置上数字不对就输出,如果都正确,就没有漏的数字,输出n+1


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


你可能感兴趣的:(LeetCode,first,Missing,Positi)