My easy to understand java solution with explanation


  • -10
    D

    public class Solution {
    public int firstMissingPositive(int[] nums) {

        if(nums.length==0 )  //base case
            return 1;
       
        if(nums.length==1)   //base case
        {
            if(nums[0]<=0 || nums[0]>=2)
                return 1;
            else
                return 2;
        }
        
        Arrays.sort(nums);  //sorts the numbers in ascending order
        int i=0;
        
        while(nums[i]<=0)   //ignore all numbers <= 0
            i++;
        
        if(nums[i]>=2)      //if first +ve number is 2 then answer is 1
            return 1;
            
        while(i<nums.length)    
        {   
             if(i>=1 && nums[i-1]>0 && (nums[i]-nums[i-1]>1))
                return nums[i-1]+1;
             i++;
         }
        
        return nums[i-1]+1;
        
    }
    

    }


Log in to reply
 

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