My Simple Java Solution with O(n) time and O(1) space


  • 0
    C
        public int firstMissingPositive(int[] nums) {
            
            for(int i=0; i<nums.length; i++){
                int num = nums[i];
                while(num>0 && num<=nums.length && nums[num-1]!=num){
                    int temp = nums[num-1];
                    nums[num-1] = num;
                    nums[i] = temp;
                    num = nums[i];
                }
            }
            
            for(int i=0; i<nums.length;i++){
                if(nums[i]!=i+1){
                    return i+1;
                }
            }
            return nums.length>0?nums.length+1:1;
            
        } 
    }

Log in to reply
 

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