LeetCode75 顏色分類 (三路快排C++實現與應用)
阿新 • • 發佈:2020-10-14
三路快排是快速排序演算法的升級版,用來處理有大量重複資料的陣列。
主要思想是選取一個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--]); } } };