LeetCode75 颜色分类 (三路快排C++实现与应用)
2020-10-14 19:07
941 查看
三路快排是快速排序算法的升级版,用来处理有大量重复数据的数组。
主要思想是选取一个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--]); } } };
相关文章推荐
- leetcode刷题----75. 颜色分类 C++实现
- LeetCode75.颜色分类 C++
- LeetCode75----分类颜色(变相快排)
- LeetCode [75] 颜色分类
- LeetCode-75 颜色分类
- 【C++ STL应用与实现】1: STL概览和分类
- Leetcode 075 颜色分类 Python C++ 史上最详细题解系列(多解法)
- LeetCode75:颜色分类-C语言一次遍历求解
- Leetcode 75 颜色分类
- Leetcode 第四题实现两排序数组中位数 与C++vector应用
- leetcode 75. 颜色分类
- Leetcode 75.颜色分类 Sort Colors
- leetcode-75 颜色分类
- LeetCode 75. 颜色分类(Java 代码)
- leetcode75.颜色分类
- Leetcode 刷题之路 之 算法思想 二、排序 : 4) 75. 颜色分类【荷兰国旗问题】
- LeetCode-075-颜色分类-中等-Java实现
- LeetCode75. 颜色分类
- 【算法——Python实现】快速排序的优化:三路快速排序及Leetcode题目应用
- 现代分类方法在医学诊断中的应用——基于R的实现