4ms C++ solution


  • 0
    L

    class Solution {
    public:
    void sortColors(vector<int>& nums) {

        if (nums.size() == 1) {
            return;
        }
        // push a marker
        nums.push_back(3);
        for (int i = 0; i< nums.size(); i++) {
            if (nums[i] == 3) {
                nums.erase(nums.begin() + i);
                break;
            }
            if (nums[i] == 0) {
                // move it to the fornt
                nums.insert(nums.begin(), 0);
                nums.erase(nums.begin() + i + 1);
                //i--;
            }
            if (nums[i] == 2) {
                // move it to the end
                nums.push_back(2);
                nums.erase(nums.begin() + i);
                i--;
            }
        }
    }
    

    };


Log in to reply
 

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