75. Sort Colors

Given an array 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.

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

Note: You are not suppose to use the library's sort function for this problem.

Example:

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Follow up:

  • A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's, then 1's and followed by 2's.

  • Could you come up with a one-pass algorithm using only constant space?

// Naive Solution
void sortColors(vector<int>& nums) { // time: O(n); space: O(1)
    vector<int> cnt(3, 0);
    for (int num : nums) ++cnt[num];
    int idx = 0;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < cnt[i]; ++j) {
            nums[idx++] = i;
        }
    }
}

如果i和left或者right一樣的話swap就沒意義。i-- 是因為經過swap之後,在index = i的數是剛換過來的數,還沒處理過。

// One Pass
void sortColors(vector<int>& nums) { // time: O(n); space: O(1)
    int left = 0, right = nums.size() - 1;
    for (int i = 0; i <= right; ++i) {
        if (nums[i] == 0 && i != left) {
            swap(nums[i--], nums[left++]);
        } else if (nums[i] == 2 && i != right) {
            swap(nums[i--], nums[right--]);
        }
    }
}
void sortColors(vector<int>& nums) { // time: O(n); space: O(1)
    int i = 0, j = 0, k = nums.size() - 1;
    while (j <= k) {
        if (nums[j] == 0) {
            swap(nums[i++], nums[j++]);
        } else if (nums[j] == 2) {
            swap(nums[j], nums[k--]);
        } else {
            ++j;
        }
    }
}

Last updated

Was this helpful?