leetcode-First Missing Positive

Difficulty: Hard

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.

class Solution {
public:
    int firstMissingPositive(vector<int>& nums) {
        if(nums.empty())
            return 1;
        int maxp=nums[0];
        int size=nums.size();
        for(int i=0;i<size;++i)
            maxp=max(maxp,nums[i]);
        if(maxp<=0)
            return 1;
        int bitmap[maxp/32+1]={0};
    
        for(auto &e:nums)
            if(e>0)
                bitmap[e/32]|=(1<<(e%32));
                
        for(int i=1;i<=maxp;++i)
            if((bitmap[i/32]&(1<<(i%32)))==0)
                return i;
        return maxp+1;        
    }
};


你可能感兴趣的:(leetcode-First Missing Positive)