首页 > 其他 > 详细

LeetCode:Sort Colors

时间:2014-11-04 13:11:51      阅读:280      评论:0      收藏:0      [点我收藏+]

题目描述:

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

原文:http://blog.csdn.net/yao_wust/article/details/40782385

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!