[leetcode_75]Sort Colors

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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;
        }
    }
};
Licensed under CC BY-NC-SA 4.0