Java solution, easy to understand


  • 0
    X
    public void sortColors(int[] nums) {
            int red=0, white=0, blue=0;
            for(int num : nums) {
                if(num == 0) red++;
                else if(num == 1) white++;
                else if(num == 2) blue++;
            }
            int index = 0;
            while(red-- > 0) {
                nums[index++] = 0;
            }
            while(white-- > 0) {
                nums[index++] = 1;
            }
            while(blue-- > 0) {
                nums[index++] = 2;
            }
        }

  • 0
    L

    this is too simple,but it is not this excerise's aim for us to get.


  • 0
    T

    Agreed, it says "objects colored red, white or blue" which means that you have class Obj { int color }; in which case you can't simply just say nums[index++] = new Obj(color=1);.


Log in to reply
 

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