C++ Solution Using Set


  • -1
    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            set<int> s;
            int mi=INT_MAX,ma=0,x=0,n=nums.size();
            if(n==0) return 1;
            for(int i=0;i<n;++i){
                if(nums[i]>0){
                    s.insert(nums[i]);
                    mi=min(mi,nums[i]);
                    ma=max(ma,nums[i]);
                }
            }
            if(mi!=1) return 1;
            auto it=s.begin(),ie=s.end();
            for(int i=mi;i<=ma&&it!=ie;++i,++it)
                if(*it!=i) return i;
            return ma+1;
        }
    };

  • 0
    V

    with the set, it's not constant space as required.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.