[LeetCode] Sort Colors
2015-06-09 14:31
323 查看
The hints on below the problem have suggested a two-pass solution.
Now I will focus on the one-pass solution.
The one-pass solution has no mystery. Just swap all 0's to the left and all 2's to the right and the 1's will automatically fall in the middle.
Now comes the following code. You may play with it using some examples on a paper to see how it works.
Now I will focus on the one-pass solution.
The one-pass solution has no mystery. Just swap all 0's to the left and all 2's to the right and the 1's will automatically fall in the middle.
Now comes the following code. You may play with it using some examples on a paper to see how it works.
void sortColors(vector<int>& nums) { int red = 0, blue = nums.size() - 1; for (int i = 0; i <= blue; i++) { while (nums[i] == 2 && i < blue) swap(nums[i], nums[blue--]); while (nums[i] == 0 && i > red) swap(nums[i], nums[red++]); } }
相关文章推荐
- 随机森林-机器学习
- android studio 快捷键设置为eclipse的习惯
- 48. Rotate Image
- Tomcat启动的时候报 validateJarFile(xxxx) jar not loaded
- 利用LD_PRELOAD进行hook
- 陈怡暖:(午评)美元再度大跌,金银反攻受限
- android平台获取手机IMSI,IMEI ,序列号,和 手机号的方法
- CentOS 6.5安全加固及性能优化(推荐)
- Makefile中的wildcard用法
- MediaCodec 实例
- 3.MFC的运行流程
- 运行时异常与一般异常有何异同?
- spring MVC 2-helloword 入门
- 如何在magento模板文件中获取controller名称,action名称和module name
- JavaBean的详细及引用
- jQuery UI dialog 的使用总结
- Android网络连接之HttpURLConnection和HttpClient
- scala快速学习笔记(一):变量函数,操作符,基本类型
- python 遍历删除日志
- 扫描二维码自动识别手机系统(Android/IOS)跳转不同页面