-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray>Sort Colors
56 lines (51 loc) · 1.24 KB
/
Array>Sort Colors
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution {
public:
void sortColors(vector<int>& nums) {
// using counting sort
int red = 0;
int white = 0;
int blue = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == 0) {
red++;
}
else if(nums[i] == 1) {
white++;
}
else {
blue++;
}
}
for(int i = 0; i < nums.size(); i++) {
if(red) {
nums[i] = 0;
red--;
}
else if(white) {
nums[i] = 1;
white--;
}
else {
nums[i] = 2;
blue--;
}
}
// using Dutch National Flag Algorithm
int n = nums.size();
int low = 0, mid = 0, high = n-1;
while(mid <= high) {
if(nums[mid] == 0) {
swap(nums[low++], nums[mid++]);
// low++;
// mid++;
}
else if(nums[mid] == 2) {
swap(nums[mid], nums[high--]);
// high--;
}
else {
mid++;
}
}
}
};