Three colors: red, white, and blue, represented by 0, 1, and 2 respectively.
Given an array of 0s, 1s, and 2s, sort it – but you cannot use any built-in sorting library.
The approach is to traverse the array, count the occurrences of 0, 1, and 2, then overwrite the original array accordingly.
Code below:
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;
}
}
};
|