首页 » 编程之美 » 正文

[leetcode_75]Sort Colors

red white blue 三种颜色
分别用0 1 2代表
输入一个0 1 2 的数组,请排序。
但是不允许用封装好的库。
具体的方法是遍历该数组对012进行计数,然后对原数组覆盖即可。
附上代码:

class Solution {
public:
    void sortColors(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int count0 = 0;
        int count1 = 0;
        int count2 = 0;
        for(int i = 0;i < n;i++)
        {
            switch(A[i])
            {
                case 0:
                    count0++;
                    break;
                case 1:
                    count1++;
                    break;
                case 2:
                    count2++;
                    break;
            }
        }
        for(int i = 0;i < count0;i++)
        {
            A[i] = 0;
        }
        for(int i = count0;i < count0 + count1;i++)
        {
            A[i] = 1;
        }
        for(int i = count0 + count1;i < count0 + count1 +count2;i++)
        {
            A[i] = 2;
        }
    }
};

发表评论