forked from MisterBooo/LeetCodeAnimation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
executable file
·52 lines (41 loc) · 1.05 KB
/
main.cpp
File metadata and controls
executable file
·52 lines (41 loc) · 1.05 KB
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
/// Source : https://leetcode.com/problems/sort-colors/description/
/// Author : liuyubobobo
/// Time : 2017-11-13
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// Counting
// Time Complexity: O(n)
// Space Complexity: O(3)
class Solution {
public:
void sortColors(vector<int> &nums) {
int count[3] = {0};
for(int i = 0 ; i < nums.size() ; i ++){
assert(nums[i] >= 0 && nums[i] <= 2);
count[nums[i]] ++;
}
int index = 0;
for(int i = 0 ; i < count[0] ; i ++)
nums[index++] = 0;
for(int i = 0 ; i < count[1] ; i ++)
nums[index++] = 1;
for(int i = 0 ; i < count[2] ; i ++)
nums[index++] = 2;
}
};
void printArr(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<int> vec1 = {2, 2, 2, 1, 1, 0};
Solution().sortColors(vec1);
printArr(vec1);
vector<int> vec2 = {2};
Solution().sortColors(vec2);
printArr(vec2);
return 0;
}