LeetCode75 颜色分类 (三路快排C++实现与应用)

三路快排是快速排序算法的升级版,用来处理有大量重复数据的数组。

主要思想是选取一个key,小于key的丢到左边,大于key的丢到右边,递归实现即可。

具体操作过程参考:https://blog.csdn.net/k_koris/article/details/80585979

C++代码:

// Author : RioTian
// Time : 20/10/14
// #include <bits/stdc++.h> 研究算法就不开万能头文件了
#include <iostream>
using namespace std;
void swap(int &a, int &b) {
    int t = a;
    a = b, b = t;
}
void Print(int a[]) {
    for (int i = 0; i < 12; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
}
void trisort(int *a, int low, int hight) {
    if (low >= hight) return;
    int key = a[low];
    int i = low, j = low;
    int k = hight;
    while (i <= k) {
        if (a[i] < key)
            swap(a[i++], a[j++]);
        else if (a[i] > key)
            swap(a[i], a[k--]);
        else
            i++;
    }
    
    // 运行过程输出
    printf("Key %d: ", key);
    Print(a);
    
    trisort(a, low, j);
    trisort(a, k + 1, hight);
}
int main() {
    // freopen("in.txt","r",stdin);
    ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    int a[] = {5, 9, 0, 1, 6, 3, 8, 7, 2, 4, 4, 4};
    trisort(a, 0, 11);
    for (int i = 0; i < 12; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
}

LeetCode75 颜色分类

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

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

注意:
不能使用代码库中的排序函数来解决这道题。

示例:

输入:

[2,0,2,1,1,0]

输出:

[0,0,1,1,2,2]

进阶:

  • 一个直观的解决方案是使用计数排序的两趟扫描算法。
    首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。
  • 你能想出一个仅使用常数空间的一趟扫描算法吗?

代码:

class Solution {
public:
    void swap(int &a, int &b) {
        int t = a;
        a = b, b = t;
    }
    void sortColors(vector<int> &nums) {
        int i = 0, j = 0, k = nums.size() - 1;
        int key = 1;
        while (i <= k) {
            if (nums[i] < key)
                swap(nums[i++], nums[j++]);
            else if (nums[i] == key)
                ++i;
            else
                swap(nums[i], nums[k--]);
        }
    }
};
原文地址:https://www.cnblogs.com/RioTian/p/13816674.html