LeetCode 75. Sort Colors

Given an array with n objects colored red, white or blue, sort them 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.


// I didn't pass this question for several tests.

// It needs three pointers. One for 0, one for 1, one for 2.


/ red 0, white 1, blue 2
#include <vector>
#include <iostream>
using namespace std;

void sortColors(vector<int>& nums) {
    if(nums.size() <= 1) return;
    int i = 0;   // pointer for 0
    int k = nums.size() - 1;  // pointer for 2
    int j = nums.size() - 1;  // pointer for 1
    while(i <= j) {
        if(nums[i] == 0) {
            i++;
        } else if(nums[i] == 2) {
            swap(nums[i], nums[k--]);  // i is not increasing.
            if(k < j) j = k;           // update the 1's pointer.
        } else {
            swap(nums[i], nums[j--]);   // i is not increasing.
        }
    }
}

int main(void) {
    vector<int> nums{0, 2, 1, 0, 2, 2};
    sortColors(nums);
    for(int i = 0; i < nums.size(); ++i) {
        cout << nums[i] << endl;
    }
    cout << endl;
}


你可能感兴趣的:(LeetCode 75. Sort Colors)