Skip to content

Commit ff55213

Browse files
committed
Added Sort Colors
1 parent e9427bf commit ff55213

File tree

4 files changed

+73
-0
lines changed

4 files changed

+73
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#include <vector>
2+
3+
class Solution {
4+
public:
5+
void sortColors(std::vector<int>& nums) {
6+
int counts[3] = {0, 0, 0};
7+
8+
for (int color : nums) {
9+
counts[color]++;
10+
}
11+
12+
int R = counts[0], W = counts[1], B = counts[2];
13+
14+
for (int i = 0; i < R; i++) {
15+
nums[i] = 0;
16+
}
17+
for (int i = R; i < R + W; i++) {
18+
nums[i] = 1;
19+
}
20+
for (int i = R + W; i < nums.size(); i++) {
21+
nums[i] = 2;
22+
}
23+
}
24+
};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public void sortColors(int[] nums) {
3+
int[] counts = new int[3];
4+
5+
for (int color : nums) {
6+
counts[color]++;
7+
}
8+
9+
int R = counts[0], W = counts[1], B = counts[2];
10+
11+
for (int i = 0; i < R; i++) {
12+
nums[i] = 0;
13+
}
14+
for (int i = R; i < R + W; i++) {
15+
nums[i] = 1;
16+
}
17+
for (int i = R + W; i < nums.length; i++) {
18+
nums[i] = 2;
19+
}
20+
}
21+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
var sortColors = function(nums) {
2+
let counts = [0, 0, 0];
3+
4+
for (let color of nums) {
5+
counts[color]++;
6+
}
7+
8+
let R = counts[0], W = counts[1], B = counts[2];
9+
10+
nums.fill(0, 0, R);
11+
nums.fill(1, R, R + W);
12+
nums.fill(2, R + W, R + W + B);
13+
};
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution:
2+
def sortColors(self, nums: List[int]) -> None:
3+
"""
4+
Do not return anything, modify nums in-place instead.
5+
"""
6+
counts = [0, 0, 0]
7+
8+
for color in nums:
9+
counts[color] += 1
10+
11+
R, W, B = counts
12+
13+
nums[:R] = [0] * R
14+
nums[R:R+W] = [1] * W
15+
nums[R+W:] = [2] * B

0 commit comments

Comments
 (0)