生活随笔
收集整理的這篇文章主要介紹了
力扣算法题—075颜色分类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個包含紅色、白色和藍色,一共?n?個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,并按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、?1 和 2 分別表示紅色、白色和藍色。
注意:
不能使用代碼庫中的排序函數來解決這道題。
示例:
輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
進階:
- 一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然后按照0、1、2的排序,重寫當前數組。 - 你能想出一個僅使用常數空間的一趟掃描算法嗎
1 #include
"_000庫函數.h"
2
3 //本來使用sort函數簡單無比
4 //但是題目要求不讓使用排序函數
5
6 //解法一:計數再生成【兩趟掃描】
7
8 //class Solution {
9 //public:
10 // void sortColors(vector<int>& nums) {
11 // int r = 0, w = 0, b = 0;//三種顏色出現次數計數
12 // for (auto a : nums)
13 // if (a == 0)++r;
14 // else if (a == 1)++w;
15 // else ++b;
16 // nums.clear();//重置
17 // nums.insert(nums.end(), r, 0);
18 // nums.insert(nums.end(), w, 1);
19 // nums.insert(nums.end(), b, 2);
20 // }
21 //};
22
23 //解法二,使用一趟掃描法
24 class Solution {
25 public:
26 void sortColors(vector<
int>&
nums) {
27 int n =
nums.size();
28 for (
int i =
0;i<
n;){
29 vector<
int>::iterator p = nums.begin() +
i;
30 if (nums[i] ==
0) {
31 nums.erase(p, p +
1);
//刪除
32 nums.insert(nums.begin(),
1,
0);
//前插
33 ++
i;
34 }
35 else if (nums[i] ==
2) {
36 nums.erase(p, p +
1);
//刪除
37 nums.insert(nums.end(),
1,
2);
//后插
38 --
n;
39 }
40 else//讓1保留在原位
41 ++
i;
42 }
43 }
44 };
45
46
47 void T075() {
48 Solution s;
49 vector<
int>
v;
50 v = {
2,
0,
2,
1,
1,
0 };
51 s.sortColors(v);
52 for (auto a : v)
53 cout << a <<
", ";
54 cout <<
endl;
55 }
?
轉載于:https://www.cnblogs.com/zzw1024/p/10710984.html
總結
以上是生活随笔為你收集整理的力扣算法题—075颜色分类的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。