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?

思路: 使用两个指针,分别指向最后一个红色的后一个位置,以及第一个蓝色蓝色的前一个位置。如果当前扫描到的元素是红色,那么与第一个指针互换,若为蓝色,与蓝色头部指针互换,若为白色,不做任何操作。

class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
int redTail = ;
int blueHead = n-;
int tmp; for(int i = ; i <= blueHead;){
if(nums[i]==){//当前是红色
if(nums[redTail]==){//红色尾指针指向红色(说明没有白色)
redTail++;
i++; //不处理当前元素
continue;
} tmp = nums[redTail];
nums[redTail] = nums[i];
redTail++;
if(tmp==){ //红色尾指针指向白色
nums[i] = tmp; //交换红色和白色
i++;
}
else{ //红色尾指针指向蓝色(说明目前没有白色)
nums[i] = nums[blueHead]; //把blueHead处的元素放到i
nums[blueHead]=tmp; //把蓝色放到blueHead处
blueHead--;
}
}
else if(nums[i]==){//如果当前是白色,不处理当前元素
i++;
}
else{ //如果当前是蓝色
tmp = nums[blueHead];
nums[blueHead] = nums[i];//把蓝色放到blueHead处
nums[i] = tmp;//把blueHead处的元素放到i
blueHead--;
}
}
}
};

最新文章

  1. 区间K 大数查询
  2. boost array使用
  3. hibnate 创建表的时候type=innodb报错
  4. word转html方法
  5. 每天一个linux命令(52):scp命令
  6. Coursera台大机器学习课程笔记14 -- Validation
  7. POJ2451 Uyuw&#39;s Concert(半平面交)
  8. get the runing time of C++ console program.
  9. key 限制字符的输入
  10. 利用python进行折线图,直方图和饼图的绘制
  11. ACM——五位以内的对称素数
  12. ☀【移动】Google Maps JavaScript API v3
  13. 解决 SQL Server 耗尽内存的情况
  14. postgresql赋予/撤消 用户权限
  15. wpf之数据触发器DataTrigger
  16. JavaScript基础学习(五)&mdash;其他引用类型
  17. [LeetCode] Next Closest Time 下一个最近时间点
  18. c/c++ 浅拷贝
  19. UIButton高亮状态卡顿
  20. [转] Mac下 快速写博客的软件 MarsEdit

热门文章

  1. What is DB time in AWR?
  2. wordpress域名解析到了网站,但是点击其他页面会出现ip而不是域名
  3. 【备忘:待完善】nsq集群初体验
  4. oracle 卸载操作
  5. 学习FPGA,踏上一步台阶
  6. Servlet 前端后台交互
  7. Hibernate学习11——Hibernate 高级配置(连接池、log4j)
  8. 【转】JMeter-Java Sampler编写范例
  9. PdfPCell对齐方式,边框,边框颜色的使用 (转)
  10. (转)CentOS 7安装Zabbix 3.4