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

[LeetCode]Sort Colors

时间:2015-04-26 10:57:53      阅读:170      评论: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.

Note:
You are not suppose to use the library’s sort function for this problem.

简言之,这道题就是给定一个含有0,1,2三个数的序列,要求将序列重新整合,将相同的元素放在相邻位置,整体顺序依旧是0,1,2。要求不能够使用库函数中的排序算法。

思路很简单,不要拘泥于排序的思想,先遍历一遍数组,统计出0,1,2三个数各自出现的频率,然后重写数组。

void sortColors(int A[], int n) {
        int count[3] = { 0, 0, 0 };
        int i = 0;
        for (i = 0; i < n; i++){
            count[A[i]]++;
        }
        int j = 0;
        for (i = 0; i < count[0]; i++){
            A[j++] = 0;
        }
        for (i=0; i < count[1]; i++){
            A[j++] = 1;
        }
        for (i = 0; i < count[2]; i++){
            A[j++] = 2;
        }
    }

[LeetCode]Sort Colors

标签:

原文地址:http://blog.csdn.net/kaitankedemao/article/details/45286069

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