Copyright statement: This article is the original article for the blogger, without permission may not be reproduced.

**Topic description**

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

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

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

Up: Follow

Rather straight forward solution A is a two-pass algorithm using counting sort.

First, the array counting number of iterate 0 's, 1' s, and 2 'then, overwrite array with total s number of 0' s,

Then 1 'and followed by S 2' s.

You come up with an Could one-pass algorithm using only constant space?

**Two. Problem analysis**

Problems start when it comes to a group object that contains three red, white and blue color, and then to sort them out, put it plainly is the one containing only`0, 1, 2`

Array of three numbers from small to large sort.

Title: up with come an one-pass algorithm using only constant space, so can only be scanned once. The approach taken here is that statistics`0, 1, 2`

Three numbers, respectively, the number of times, and then the array nums re constructed from 0 to 2 array of arrays, this method does not use the exchange between the array elements, just scan once nums.

**Three. Sample code**

```
<iostream> #include
<vector> #include
Using Namespace STD;
ClassSolution {
Public:
VoidSortColors (Vector<Int>& nums)
{
IntSIZE = nums.size ();
IntCount[Three] = {Zero,Zero,Zero};
For(Int= IZero; SIZE < ++i; I)
++count[nums[i]];
For(Int= IZeroIndex =ZeroI; "Three++i);
For(Int= JZero; count[i] < ++j; J)
Nums[index++] = i;
}
};
```

A test result:

**Four. Summary**

This method is very much, but other solution of multi reference line.

- top
- Two

- step on
- Zero

- Last oneLeetcode note: Missing Positive First
- Next articleLeetcode note: for a Range Search

- Guess you're looking for