问题描述:
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]