Java 1ms simple non-space o(n)


  • 0
    R
    public int firstMissingPositive(int[] nums) {
        int n=nums.length;
        for(int index=0; index<n; index++){
            if(nums[index]<=n && nums[index]>0){
                if(nums[index]!=index+1 && nums[nums[index]-1]!=nums[index]){
                    int temp = nums[index];
                    nums[index]=nums[nums[index]-1];
                    nums[temp-1]=temp;
                    index--;
                }
            }
        }
        for(int index=0; index<n; index++){
            if(nums[index]!=index+1){
                return index+1;
            }
        }
        return n+1;
    }

Log in to reply
 

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