Some c++ solution (6 ms )


  • 0
    N
    public:
        int firstMissingPositive(vector<int>& nums) {
            int size = nums.size();
            
            // ordering numbers
            for( int i = 0; i < size; )
            {
                // find place to insert current number
                int j = nums[i] - 1;
                
                // if place is out-of vector range or duplicated numbers are detected 
                // then replace current number with zero and do not care of it, move to next number
                if( j < 0 || j >= size || ( nums[i] == nums[j]  && i != j ) )
                {
                    nums[i++] = 0;
                    continue;
                }
                
                // put current number to its place 
                // current is changed
                int tmp = nums[i];
                nums[i] = nums[j];
                nums[j] = tmp;          
                   
                // new current should be ignored (non-positive) or it is already in correct place
                // move to next number
                if( nums[i] <= 0 || nums[i] == i + 1 )
                {
                    ++i;
                }        
            }
            
            // find first missed number 
            for( int i = 0; i < size; ++i )
            {
                if( nums[i] != (i + 1) )
                {
                    return (i + 1);
                }
            }
            
            // nothing is found case
            return size + 1;
        }
    };```

Log in to reply
 

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