# 颜色分类

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

此题中,我们使用整数 0、 12 分别表示红色、白色和蓝色。

 

示例 1:

输入:nums = [2,0,2,1,1,0]
输出:
[0,0,1,1,2,2]

示例 2:

输入:nums = [2,0,1]
输出:
[0,1,2]

示例 3:

输入:nums = [0]
输出:
[0]

示例 4:

输入:nums = [1]
输出:
[1]

 

提示:

 

进阶:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; ``` ### after ```cpp int main() { Solution sol; int a = 3, b = 4; vector nums = {2, 0, 2, 1, 1, 0}; sol.sortColors(nums); for (auto i : nums) cout << i << " "; return 0; } ``` ## 答案 ```cpp class Solution { public: void sortColors(vector &nums) { int zero = 0, two = nums.size() - 1; int i = 0; while (i <= two) { if (nums[i] <= 1) { int temp = nums[i]; nums[i] = nums[zero]; nums[zero] = temp; zero++; i++; } else { int temp = nums[i]; nums[i] = nums[two]; nums[two] = temp; two--; } } } }; ``` ## 选项 ### A ```cpp class Solution { public: void sortColors(vector &nums) { int p0 = 0; int p1 = 0; int p2 = nums.size() - 1; while (p1 <= p2) { if (nums[p1] == 0) swap(nums[p1++], nums[p0++]); else if (nums[p1] == 2) swap(nums[p1], nums[p2--]); else p1++; } } }; ``` ### B ```cpp class Solution { public: void sortColors(vector &nums) { int a[3] = {0}; int b[3] = {0, 1, 2}; int num = 0; for (int i = 0; i < nums.size(); i++) { if (nums[i] == 0) a[0]++; if (nums[i] == 1) a[1]++; if (nums[i] == 2) a[2]++; } for (int i = 0; i < 3; i++) { for (int j = 0; j < a[i]; j++) { nums[num] = b[i]; num++; } } } }; ``` ### C ```cpp class Solution { public: void sortColors(vector &nums) { int start = 0; int end = nums.size() - 1; int temp; for (int i = 0; i < nums.size(); i++) { if (i > end) break; if (nums[i] == 2) { if (i == end) continue; temp = nums[i]; nums[i] = nums[end]; nums[end] = temp; end--; i--; } else if (nums[i] == 0) { if (i == start) continue; temp = nums[i]; nums[i] = nums[start]; nums[start] = temp; start++; i--; } } } }; ```