Easy to understand Java O(n) solution


  • 0
    A
    public void sortColors(int[] nums) {
            int c0=0,c1=0,c2=0;
            for(int i=0;i<nums.length;i++){
                if(nums[i]==0)
                c0++;
                if(nums[i]==1)
                c1++;
                if(nums[i]==2)
                c2++;
            }
            
            for(int i=0;i<nums.length;i++){
                if(i<c0)
                nums[i]=0;
                else if(i<c0+c1)
                nums[i]=1;
                else 
                nums[i]=2;
            }
        }
    

Log in to reply
 

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