Leetcode notes: Colors Sort

label LeetcodeC++Sortsortalgorithm
1111 people read comment(0) Collection report
Classification:

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 only0, 1, 2Array 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 statistics0, 1, 2Three 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:

Write the picture here.

Four. Summary

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

top
Two
step on
Zero
Guess you're looking for
View comments
* the above user comments only represent their personal views, does not represent the views or position of the CSDN website
    personal data
    • visit257118 times
    • Integral:Five thousand four hundred and twelve
    • Grade
    • Rank:2692nd name
    • original205
    • Reproduced:7
    • Translation:2
    • Comments:198
    Blog column
    Latest comments