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?
Two-pass: 统计计数
void sortColors(int* nums, int numsSize) {
int cnt0 = 0;
int cnt1 = 0;
int cnt2 = 0;
for (int i = 0; i < numsSize; ++i)
{
if (nums[i] == 0) cnt0++;
else if (nums[i] == 1) cnt1++;
else cnt2++;
}
cnt1 += cnt0;
cnt2 += cnt1;
for (int i = 0; i < numsSize; ++i)
{
if (i < cnt0) nums[i] = 0;
else if (i < cnt1) nums[i] = 1;
else nums[i] = 2;
}
}One-pass: 利用三个数分别记录0,1,2前一个所在的位置
void sortColors(int* nums, int numsSize) {
int i = -1;
int j = -1;
int k = -1;
for (int n = 0; n < numsSize; ++n)
{
if (nums[n] == 0)
{
nums[++k] = 2;
nums[++j] = 1;
nums[++i] = 0;
}
else if (nums[n] == 1)
{
nums[++k] = 2;
nums[++j] = 1;
}
else {
nums[++k] = 2;
}
}
}
本文介绍了一种不使用库排序函数的三色排序算法,通过两种遍历方式实现:两遍法采用计数排序,一遍法则利用三个指针记录不同颜色元素的位置。
293

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



