class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        
        for(int i = 0;i < n;i++)
        {
            if(nums[i] <= 0)
                nums[i] = n + 1;
        }
        
        for (int i = 0; i < n; ++i) {
            int num = abs(nums[i]);
            if (num <= n) {
                nums[num - 1] = -abs(nums[num - 1]);
            }
        }
        
        for(int i = 0;i < n;i++)
        {
            if(nums[i] > 0)
                return i + 1;
        }
        
        return n + 1;
    }
};

运行效率:

Runtime: 100 ms, faster than 69.66% of C++ online submissions for First Missing Positive.
Memory Usage: 66.1 MB, less than 72.03% of C++ online submissions for First Missing Positive.

方法二:

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        int n = nums.size();
        for(int i = 0;i < n;i++)
        {
            while(nums[i] > 0 && nums[i] <= n && nums[i] != nums[nums[i] - 1])
                swap(nums[nums[i] - 1], nums[i]);
        }

        for(int i = 0;i < n;i++)
        {
            if(nums[i] != i+1)
                return i + 1;
        }
        return n + 1;
    }
};