Just count and fill, C++ solution, 3ms, 5 lines

  • 0

    Just count each color, then fill the array... just two pass:

        void sortColors(vector<int>& nums) {
            int counts[3] = {0,0,0};
            for(int num: nums) { counts[num]++; }
            fill(nums.begin(), nums.begin()+counts[0], 0);
            fill(nums.begin()+counts[0], nums.begin()+counts[0]+counts[1], 1);
            fill(nums.begin()+counts[0]+counts[1], nums.end(), 2);

Log in to reply

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