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.
由于只有三个数字,因此简单记录下每个数字出现的次数,然后重新构造下队列即可。
class Solution {
public:
void sortColors(int A[], int n) {
int num0=0,num1=0,num2=0;
for(int i=0;i<n;i++)
{
if(A[i]==0)
{
num0++;
}
if(A[i]==1)
{
num1++;
}
if(A[i]==2)
{
num2++;
}
}
for(int i=0;i<num0;i++)A[i]=0;
for(int i=num0;i<num0+num1;i++)A[i]=1;
for(int i=num0+num1;i<num0+num1+num2;i++)A[i]=2;
}
};