Easy Java solution by Using Hashtable


  • 1
    X
    public void sortColors(int[] nums) {
        int[] hash = new int[256];
        
        for(int num: nums)
        {
            if(num == 0)
                hash['r']++;
            else if(num == 1)
                hash['w']++;
            else
                hash['b']++;
        }
        //for()
        
        int i = 0;
        
        while(hash['r']-- > 0)
            nums[i++] = 0;
        while(hash['w']-- > 0)
            nums[i++] = 1;
        while(hash['b']-- > 0)
            nums[i++] = 2;
        
    }

Log in to reply
 

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