[LeetCode] Sort Colors 解题报告

本文介绍了一种利用一次遍历和双指针技巧来解决排序特定颜色的问题的方法,同时解释了两种不同的排序算法实现:计数排序和双指针排序。通过对比两种方法的时间复杂度和空间复杂度,本文旨在提供一种高效且空间使用优化的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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?
» Solve this problem

[解题思路]
一开始想到的就是计数排序,但是计数排序需要两边扫描,第一遍统计红,白,蓝的数目,第二遍生成新数组。

考虑到题目要求one pass。这就意味着类似于链表的双指针问题,这里也要track两个index,一个是red的index,一个是blue的index,两边往中间走。

i从0到blue index扫描,
遇到0,放在red index位置,red index后移;
遇到2,放在blue index位置,blue index前移;
遇到1,i后移。
扫描一遍得到排好序的数组。时间O(n),空间O(1),

[Code]
two-pass solution, Counting sort solution
1:       void sortColors(int A[], int n) {   
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int red=0, white =0, blue=0;
5: for(int i =0; i < n; i++)
6: {
7: switch(A[i])
8: {
9: case 0:
10: red++;break;
11: case 1:
12: white++;break;
13: case 2:
14: blue++;break;
15: }
16: }
17: for(int i =0; i<n; i++)
18: {
19: if(red>0)
20: {
21: A[i]=0;
22: red--;
23: continue;
24: }
25: if(white>0)
26: {
27: A[i] =1;
28: white--;
29: continue;
30: }
31: A[i]=2;
32: }
33: }


one-pass, two pointers solution
1:       void sortColors(int A[], int n) {   
2: // Start typing your C/C++ solution below
3: // DO NOT write int main() function
4: int redSt=0, bluSt=n-1;
5: int i=0;
6: while(i<bluSt+1)
7: {
8: if(A[i]==0)
9: {
10: std::swap(A[i],A[redSt]);
11: redSt++;
12: i++;
13: continue;
14: }
15: if(A[i] ==2)
16: {
17: std::swap(A[i],A[bluSt]);
18: bluSt--;
19: continue;
20: }
21: i++;
22: }
23: }


转载于:https://www.cnblogs.com/codingtmd/archive/2013/01/06/5078952.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值