首页 > 代码库 > LeetCode:Sort Colors

LeetCode: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.


思路:运用counting sort的思想。先遍历一遍数组,分别统计出0,1,2的个数n0,n1,n2。然后分别将n0个0,n1个1,n2个2写入到原数组中。


代码:

void Solution::sortColors(int A[], int n)
{
    int zero = 0;
    int one = 0;
    int two = 0;
    int i;
    for(i = 0;i < n;i++)
    {
        if(A[i] == 0)
            zero++;
        else if(A[i] == 1)
            one++;
        else if(A[i] == 2)
            two++;
    }
    i = 0;
    while(zero > 0)
    {
        A[i] = 0;
        i++;
        zero--;
    }
    while(one > 0)
    {
        A[i] = 1;
        i++;
        one--;
    }
    while(two > 0)
    {
        A[i] = 2;
        i++;
        two--;
    }
}


LeetCode:Sort Colors