Java 95.5% Solution


  • 0
    R

    1.Move negative & 0 to the end of the array while recording the negative number 2.Set positive values of corresponding index occured to negative
    3.Find the first positive(which does not occur) and return its index

     public int firstMissingPositive(int[] nums) {
            int negative=0;
            int l=nums.length;
            int i=0;
            while(i<l-negative){
                if(nums[i]<=0){
                    negative+=1;
                    int tmp=nums[i];
                    nums[i]=nums[l-negative];
                    nums[l-negative]=tmp;
                }
                else i+=1;
            }
           for(int j=0;j<l-negative;j++){
               int value=Math.abs(nums[j]);
               if(value-1<l-negative&&nums[value-1]>0)
               nums[value-1]=-nums[value-1];
           } 
           for(int j=0;j<l-negative;j++){
               if(nums[j]>0)
               return j+1;
           }
           return l-negative+1;
        }
    

Log in to reply
 

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