问题描述:
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?
问题分析:
一开始没看follow up,想到只是单纯的数字由小到大的排序问题,直接随便写了个冒泡排序,过了只要3ms,然后看到说直观的做法是使用计数排序【话说直观为何会想到这个...】,所以又写了下计数,时间跟普通的冒泡也差不多,还是3ms。某种程度上来说,冒泡跟计数一样,都是扫两遍,所以时间差不多道也可以理解。
具体实现:
计数:
class Solution {
public:
void sortColors(vector
& nums) {
int i=0;
int j=0;
int k=0;
for(int p=0;p
冒泡:
class Solution {
public:
void sortColors(vector
& nums) {
int tmp = -1;
for(int i=0;i
nums[j])
{
tmp = nums[j];
nums[j] = nums[i];
nums[i] = tmp;
}
}
}
}
};
双冒泡:
class Solution {
public:
void sortColors(vector
& nums) {
int low = 0;
int high = nums.size()-1;
int tmp,j;
while(low
nums[j+1])
{
tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
high--;
for(j = high;j>low;--j)
{
if(nums[j]
本文介绍了一种特定场景下的排序算法——三色排序,该算法针对红、白、蓝三种颜色的对象进行排序,使得相同颜色的对象相邻,并按红、白、蓝的顺序排列。文中提供了几种不同的实现方式,包括计数排序、冒泡排序以及一种利用两个指针的优化方法。
530

被折叠的 条评论
为什么被折叠?



