leetcode - Sort Colors
2015-08-07 17:16
351 查看
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?
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?
class Solution { public: void sortColors(int A[], int n) { int r = 0,w = 0,b = 0; for (int i = 0; i < n; i++) { if(A[i] == 0) r += 1; if(A[i] == 1) w += 1; if(A[i] == 2) b += 1; } for (int i = 0; i < n; i++) { A[i] = i < r ? 0 : (i < r + w ? 1 : 2); } } };
相关文章推荐
- “出轨照”背后的真相:防骗启示录之相册病毒报告
- 一只青蛙一次可以跳上 1 级台阶,也可以跳上2 级。求该青蛙跳上一个n 级的台阶总共有多少种跳法
- JavaEE拾遗01--异步上传文件
- Date和Calendar
- 上拉电阻下拉电阻的总结
- 自动取款机 银行铁路机器操作指南
- bzoj2118
- Android Studio配置OpenCV开发环境
- oc中的内存管理的初步
- 一个QT 3D转动控件
- c# ros
- HDU 5360 Hiking(2015多校联合)
- bzoj2118 分类: bzoj 2015-08-07 17:15 78人阅读 评论(0) 收藏
- 嵌入式中通讯协议的设计(转)
- echarts 点击事件
- UnityShader实例11:积雪材质
- 【Android应用开发技术:用户界面】自定义View类设计
- 也谈不甘
- 静帧效果图——Maya的节点材质案例
- 让你网页同时兼容FireFox和IE