# 【LeetCode】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]

• 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?

1，当current遇到0时，则这个0和zero位置元素交换，并且zero后移，

其中如果交换后，current位置仍为0，则current需要后移一位

2，若curren处为1，则current后移

3，若current处为2，则这个2和two位置元素交换，并且two前移

class Solution {
public:
void sortColors(vector<int>& nums) {
int zero = 0, current = 0, two = nums.size() - 1;
while (current <= two) {
if (nums[current] == 0) {
swap(nums[current], nums[zero]);
if (nums[current] == 0) {
++current;
}
++ zero;
} else if (nums[current] == 1) {
++ current;
} else {
swap(nums[current], nums[two]);
-- two;
}
}
}
};

01-15 68
10-16 152
12-30 129
11-17 1124
09-17 1205