leetcode--First Missing Positive

1.题目描述

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.

2.解法分析

解法:遍历数组,将遇到的正数放到对应的位置,也就是正数i应该放在A[i-1]处。

为什么呢?最直接的算法莫过于排序了,但是时间复杂度满足不了要求,然后就是hash了,但是普通的hash无法满足常数量级的额外空间要求,那么这个题目的思路就是用数组本身作为hash的空间,然后就有了这个解法。

class Solution {
public:
    int firstMissingPositive(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n==0)return 1;
        
        int i=0;
        while(i<n)
        {
            if(A[i]>0&&A[i]<=n)
            {
                if(A[i]!=A[A[i]-1])
                {
                    int temp=A[i];
                    A[i]=A[A[i]-1];
                    A[temp-1]=temp;
                    continue;
                }
                else i++;
                
            }
            
            else 
            {
                A[i]=0;i++;
            }
        }
        
        i=0;
        while(i<n)
        {
            if(A[i]!=(i+1))return i+1;
            i++;
        }
        
        return n+1;
    }
};
原文地址:https://www.cnblogs.com/obama/p/3280226.html