# LCP075 LeetCode 75. Sort Colors

198人阅读 评论(0)

Total Accepted: 100513 Total Submissions: 287992 Difficulty: Medium

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.

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?

Subscribe to see which companies asked this question

Follow up 的意思是遍历一遍数组，然后统计出0, 1, 2的个数，然后再重头挨个把数字置换成相应个数的0, 1, 2

int zerocnt = 0, onecnt = 0, twocnt = 0;
for (int i = 0, i < nums.size(); i++)
{
if (nums[i] == 0)
zerocnt++;
if (nums[i] == 1)
onecnt++;
if (nums[i] == 2)
twocnt++;
}
for (int i = 0; i < zerocnt; i++)
nums[i] = 0;
for (int i = zerocnt; i < zerocnt+onecnt; i++)
nums[i] = 1;
for (int i = zerocnt+onecnt; i < nums.size(); i++)
nums[i] = 2;

balabalabala。。。。一阵手动执行代码之后发现，让y来作为主动指针，当*y = 0，跟x换，当*y = 2，跟z换。这样的效率要高一些。

class Solution {
public:
void swaptwo(int &a, int &b)
{
int temp = a;
a = b;
b = temp;
}
void sortColors(vector<int>& nums)
{
if (nums.size() == 1)
return;
if (nums.size() == 2)
{
if (nums[0] > nums[1])
swaptwo(nums[0], nums[1]);
return;
}
int x, y, z;
for (x = 0; nums[x] == 0; x++);
for (y = x; nums[y] == 1; y++);
for (z = nums.size() - 1; nums[z] == 2; z--);
while (y <= z)
{
if (nums[y] == 2)
{
swaptwo(nums[y], nums[z]);
for (z = z - 1; nums[z] == 2; z--);
}
if (nums[y] == 0)
{
swaptwo(nums[y], nums[x]);
for (y = y + 1; nums[y] == 1; y++);
x++;
}
if (nums[y] == 1)
{
for (y = y + 1; nums[y] == 1; y++);
}
}
}
};

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：14745次
• 积分：494
• 等级：
• 排名：千里之外
• 原创：24篇
• 转载：4篇
• 译文：11篇
• 评论：8条
文章分类
阅读排行
最新评论