My c++ O(n) solution


  • 0
    P
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int red(0);
            int white(0);
            int blue(0);
            for(auto x:nums)
            {
                if(x == 0)red++;
                if(x == 1)white++;
                if(x == 2)blue++;
            }
            int cnt(0);
            while(red--)
                nums[cnt++] = 0;
            while(white--)
                nums[cnt++] = 1;
            while(blue--)
                nums[cnt++] = 2;
        }
    };

Log in to reply
 

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