simple and easy not smart but time O(n) space O(1)


  • 0
    Z
    public:
        void sortColors(vector<int>& nums) {
            int red=0, white=0, blue=0;
            for(int i=0; i<nums.size(); i++){
                if(nums[i]==0) red++;
                else if(nums[i]==1) white++;
                else if(nums[i]==2) blue++;
            }
            int i=0;
            while(red>0 ||white>0 || blue >0  && i<nums.size()){
                if(red>0){ nums[i]=0; red--;}
                else if(white>0){ nums[i]=1; white--;}
                else if(blue>0){ nums[i]=2; blue--;}
                i++;
            }
        }
    };

Log in to reply
 

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