-
Notifications
You must be signed in to change notification settings - Fork 28
/
Sort_Colors.cpp
41 lines (40 loc) · 953 Bytes
/
Sort_Colors.cpp
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
35
36
37
38
39
40
41
// using two pointers
class Solution {
public:
void sortColors(vector<int>& arr) {
if(arr.empty()) return;
int n = arr.size();
int left = -1, right = 0;
while(right < n) {
if(arr[right] == 0) {
swap(arr[++left], arr[right++]);
} else {
++right;
}
}
right = left + 1;
while(right < n) {
if(arr[right] == 1) {
swap(arr[++left], arr[right++]);
} else {
++right;
}
}
}
};
// counting sort
class Solution {
public:
void sortColors(int A[], int n) {
int count[3] = {0};
for(int i = 0; i < n; ++i) {
count[A[i]]++;
}
int indx = 0;
for(int i = 0; i < 3; ++i) {
while(count[i]--) {
A[indx++] = i;
}
}
}
};