Share my one loop C++ solution


  • 3
    H
    class Solution {
    public:
        void sortColors(vector<int>& nums) {
            int s[3] = {0,0,0};
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] == 0) {
                    nums[s[2]++] = 2;
                    nums[s[1]++] = 1;
                    nums[s[0]++] = 0;
                } else if (nums[i] == 1) {
                    nums[s[2]++] = 2;
                    nums[s[1]++] = 1;
                } else {
                    nums[s[2]++] = 2;
                }
            }
        }
    };

  • 0
    M

    Hi can you explain your code? I found this solution is special.But I cannot quite catch how you work this out.


  • 0
    H

    s[0] stands for the next position of last 0 in the sorted part, so does s[1] and s[2]. Before insert a number into the sorted part, you should have a space for it. So when you insert 0 you should move the part of 1s and 2s back one step. Then you can insert 0 to replace the first 1 where is next to the last 0 in the sorted part. There is an example:1 2 2 2 0 (1 2 2 2 is sorted part)=====> 1 2 2 2 2 =====> 1 1 2 2 2 =====> 0 1 2 2 2


  • 0
    M

    thank you for your explanation.


  • 0
    H

    My pleasure. ^_^


Log in to reply
 

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