麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學院 > 開發設計 > 正文

LeetCode 75. Sort Colors

2019-11-11 05:15:57
字體:
來源:轉載
供稿:網友

描述 Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.

Here, we will use the integers 0, 1, and 2 to rePResent the color red, white, and blue respectively.

Note: You are not suppose to use the library’s sort function for this problem.

Follow up: A rather straight forward solution is a two-pass algorithm using counting sort. First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s.

Could you come up with an one-pass algorithm using only constant space?

分析 由于 0, 1, 2 非常緊湊,首先想到計數排序 (counting sort),但需要掃描兩遍,不符合題目要求。 由于只有三種顏色,可以設置兩個 index,一個是 red 的 index,一個是 blue 的 index,兩邊往中 間走。時間復雜度 O(n),空間復雜度 O(1)。 第 3 種思路,利用快速排序里 partition 的思想,第一次將數組按 0 分割,第二次按 1 分割,排 序完畢,可以推廣到 n 種顏色,每種顏色有重復元素的情況。

代碼

class Solution {public: void sortColors(vector<int>& nums) { const int n = nums.size(); int red = 0; int blue = n - 1; for (size_t i = 0; i < blue + 1;) { if (nums[i] == 0) swap(nums[i++], nums[red++]); else if (nums[i] == 2) swap(nums[i], nums[blue--]); else i++; } }};
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 国产精品久久久久久238 | 国产精品欧美久久久久一区二区 | 91女上位 在线播放 性欧美日本 | 久久久久久久久久综合 | 精品中文字幕在线播放 | 日韩三级伦理在线观看 | 在线免费视频a | 欧美亚洲一区二区三区四区 | 成人性视频在线 | 日韩精品久久久久久久电影99爱 | 成人免费福利网站 | 成人毛片一区 | 久久久中精品2020中文 | 日本高清在线免费 | 香蕉视频网站在线观看 | 欧美综合在线观看视频 | 中文字幕在线播放一区 | 手机黄色小视频 | 久久成人福利 | 日韩一级成人 | 欧美国产成人在线 | 成人偷拍片视频在线观看 | 国产精品视频一区二区三区四区五区 | 国产乱乱视频 | 伊人亚洲精品 | www亚洲成人 | 国产91在线高潮白浆在线观看 | av电影手机在线看 | 青草伊人网| 亚洲欧美一区二区三区在线观看 | 精品国产欧美一区二区 | 久久福利剧场 | 国产精品久久久久影院老司 | 2019天天干夜夜操 | 欧美一级毛片免费观看视频 | 中文在线观看www | 最新av在线免费观看 | 日韩视频―中文字幕 | 久久精品一区二区三区国产主播 | 91社区电影| 欧美成人性色 |