# leetcode 75. Sort Colors

Posted by 111qqz on Thursday, April 13, 2017

## TOC

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.

``````/* ***********************************************
Author :111qqz
Created Time :2017年04月13日 星期四 18时24分25秒
File Name :75.cpp
************************************************ */
class Solution {

public:

//思路：把0往前仍，把2往后仍
void pr(vector<int>& nums)
{
int siz = nums.size();
for ( int i = 0 ; i < siz;  i++) printf("%d%c",nums[i],i==siz-1?'\n':' ');
}
void sortColors(vector<int>& nums) {
int n = nums.size();
int l=0,r=n-1;
int cur = 0;
while (cur<r+1)
{
if (nums[cur]==0)
{
swap(nums[cur],nums[l]);
l++;
cur++;
continue;
}
if (nums[cur]==2)
{
swap(nums[cur],nums[r]);
r--;
continue;
}
cur++; //只有不交换的时候才cur++
pr(nums);
}

}

};
``````

``````/* ***********************************************
Author :111qqz
Created Time :2017年04月13日 星期四 18时24分25秒
File Name :75.cpp
************************************************ */
class Solution {

public:

//思路：把0往前仍，把2往后仍
void pr(vector<int>& nums)
{
int siz = nums.size();
for ( int i = 0 ; i < siz;  i++) printf("%d%c",nums[i],i==siz-1?'\n':' ');
}
void sortColors(vector<int>& nums) {
int n = nums.size();
int r,w,b;
r=w=b=0; //r,w,b,分别表示，当前如果要放一个相应颜色，应该放在第几个。
for ( auto x :nums)
{
if (x==0)nums[b++]=2,nums[w++]=1,nums[r++]=0;
else if (x==1) nums[b++]=2,nums[w++]=1;
else nums[b++]=2;  //因为b,r,w前进的速度是不一样的，取决于当前的值
// printf("r:%d  w:%d b:%d ",r,w,b);pr(nums);
}

}

};
``````

「真诚赞赏，手留余香」