问题
给定一个包含红色、白色和蓝色、共 n 个元素的数组 nums ,原地 对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
必须在不使用库内置的 sort 函数的情况下解决这个问题。
示例 1:
输入:nums = [2,0,2,1,1,0]
输出:[0,0,1,1,2,2]
示例 2:
输入:nums = [2,0,1]
输出:[0,1,2]
分析
不让用sort,那就快排。模板题。
代码
class Solution {
public:vector<int> q;int q_n = 0;void quick_sort(int l, int r) {if (l >= r) {return ;}int i = l, j = r+1;int x = q[l];while(1) {do {i++;} while(i < r && q[i] < x);do {j--;} while(j > l && q[j] > x);if (i >= j) {break;}int t = q[i]; q[i] = q[j]; q[j] = t;}int t = q[l]; q[l] = q[j]; q[j] = t;int s = j;quick_sort(l, s-1);quick_sort(s+1, r);}void sortColors(vector<int>& nums) {this->q = nums; this->q_n = nums.size();quick_sort(0, q_n-1);nums = q;}
};