Sort Colors
来源:互联网 发布:炉石大数据各数据意义 编辑:程序博客网 时间:2024/06/05 16:27
题目描述:
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.
click to show follow up.
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?
分析:
因为题目要求只能扫一次,所以用a,b,c分别记录当前0,1,2排序后的最后一位得下标,如a表示最后一个0的下标,不断更新即可。
代码如下:
void sortColors(vector<int>& num) { int len=num.size(); int a=0,b=0,c=0; for(int i=0;i<len;i++){ if(num[i]==0){ num[c++]=2; num[b++]=1; num[a++]=0; } else if(num[i]==1){ num[c++]=2; num[b++]=1; } else if(num[i]==2){ num[c++]=2; } } }
- Sort Colors
- sort colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- Sort Colors
- The Bottom of a Graph POJ
- 初学者易上手的SSH-struts2 05拦截器与自定义拦截器
- UnityShader初级篇——BlinnPhong光照模型
- 特征工程(2)
- OkHttp用法
- Sort Colors
- 布局侧边栏
- 博弈问题外挂-SG函数
- Class的 getSuperclass与getGenericSuperclass区别和如何获取泛型参数类型
- BZOJ
- RecyclerView
- Android---Bannerd的基本使用
- 使可变性最小化。
- git撤销操作(git checkout; git reset)