Java solution using two for loops O(1) and O(n)


  • 0
    J
    public class Solution {
        public int firstMissingPositive(int[] nums) {
            if(nums.length == 0){
                return 1;
            }
            for (int i = 0; i < nums.length; i++) {
                while (nums[i] >= 0 && nums[i] < nums.length && nums[i] != nums[nums[i]]) {
                    int t = nums[nums[i]];
                    nums[nums[i]] = nums[i];
                    nums[i] = t;
                }
            }
            
            for (int i = 1;i<nums.length;i++){
                if(nums[i]!=i){
                    return i;
                }
            }
            return nums[0] ==  nums.length ? nums.length+1 : nums.length;
        }
    }
    
    

Log in to reply
 

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