-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsort-colors.cpp
More file actions
33 lines (29 loc) · 800 Bytes
/
Copy pathsort-colors.cpp
File metadata and controls
33 lines (29 loc) · 800 Bytes
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
/* https://leetcode.com/problems/sort-colors/ */
class Solution {
public:
void swap(vector<int>& nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
void sortColors(vector<int>& nums) {
int zero = 0, one = 0, two = nums.size() - 1;
int tmp;
for (int i = 0; i < nums.size(); i++) {
if (one > two) { break; }
switch (nums[i]) {
case 0:
swap(nums, i, zero);
zero++; one++;
break;
case 1:
one++;
break;
case 2:
swap(nums, i, two);
two--; i--;
break;
}
}
}
};