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.

每次交换使得一个数据num回到num-1的位置


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

你可能感兴趣的:(LeetCode)