LeetCode 0041 - First Missing Positive

2021-08-11 10:35:12 浏览数 (1)

First Missing Positive

Desicription

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.

Solution

代码语言:javascript复制
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[i], nums[nums[i] - 1]);
        
        for(int i = 0; i < n; i  )
            if(nums[i] != i   1) return i   1;
        
        return n   1;
    }
};

0 人点赞