Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

We will use the integers 0, 1, and 2 to represent the color red, white, and blue, respectively.


Test Cases

Input:

(int[]) nums = [2,0,2,1,1,0]

Output:

(int[]) [0,0,1,1,2,2]

Input:

(int[]) nums = [2,0,1]

Output:

(int[]) [0,1,2]

Solution

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int n0 = -1, n1 = -1, n2 = -1;
        for(int i=0; i<nums.size(); i++) {
            if (nums[i] == 0) {
                nums[++n2] = 2; nums[++n1] = 1; nums[++n0] = 0;
            } else if (nums[i] == 1) {
                nums[++n2] = 2; nums[++n1] = 1;
            } else {
                nums[++n2] = 2;
            }
        }
    }
};
class Solution {
    public void sortColors(int[] nums) {
        int n0 = -1, n1 = -1, n2 = -1;
        for(int i =0; i<nums.length; i++) {
            if (nums[i] == 0) {
                nums[++n2] = 2; nums[++n1] = 1; nums[++n0] = 0;
            }
            else if (nums[i] == 1) {
                nums[++n2] = 2; nums[++n1] = 1;
            }
            else if (nums[i] == 2) {
                nums[++n2] = 2;
            }
        }
    }
}
Time Complexity: O(n)
Space Complexity: O(1)