forked from MisterBooo/LeetCodeAnimation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain2.cpp
More file actions
executable file
·51 lines (41 loc) · 1.06 KB
/
main2.cpp
File metadata and controls
executable file
·51 lines (41 loc) · 1.06 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
/// Source : https://leetcode.com/problems/sort-colors/description/
/// Author : liuyubobobo
/// Time : 2017-11-13
#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
// Three Way Quick Sort
// Time Complexity: O(n)
// Space Complexity: O(1)
class Solution {
public:
void sortColors(vector<int> &nums) {
int zero = -1; // [0...zero] == 0
int two = nums.size(); // [two...n-1] == 2
for(int i = 0 ; i < two ; ){
if(nums[i] == 1)
i ++;
else if (nums[i] == 2)
swap( nums[i] , nums[--two]);
else{ // nums[i] == 0
assert(nums[i] == 0);
swap(nums[++zero] , nums[i++]);
}
}
}
};
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;
}