码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Sort Colors

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

标签:leetcode   algorithm   

题目描述:

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

标签:leetcode   algorithm   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!