share my one pass using count.


  • 0
    Y
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int ones = -1;
            int twos = -1;
            int threes = -1;
            for (int i = 0; i < nums.size(); ++i) {
                if (nums[i] == 0) {
                    ones++;
                    twos++;
                    threes++;
                    nums[ones] = 0;
                    if (twos > ones) nums[twos] = 1;
                    if (threes > twos) nums[threes] = 2;
                } else if (nums[i] == 1) {
                    twos++;
                    threes++;
                    nums[twos] = 1;
                    if (threes > twos) nums[threes] = 2;
                } else {
                    threes++;
                    nums[threes] = 2;
                }
          }
        }
    };
    

    This code only cost 3ms.


Log in to reply
 

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