[leetcode]Sort Colors
2015-12-19 15:31
471 查看
问题描写叙述:
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.
基本思想:
遍历一遍记录0,1,2的个数,然后利用计数排序写出代码。代码:
void sortColors(int A[], int n) { //C++ int rNum =0,wNum = 0, bNum =0; for(int i = 0; i < n; i++){ if(A[i] == 0) rNum++; else if(A[i] == 1) wNum++; else bNum++; } int rBegin = 0; int wBegin = rNum; int bBegin = rNum+wNum; //ith element i < rNum for(int i = 0; i < n; i++){ if(i < rNum) A[i] =0; else if(i < n-bNum) A[i] = 1; else A[i] =2; } }
one-pass algorithm
void sortColors(int[] A) { int i=-1, j=-1, k=-1; for(int p = 0; p < A.length; p++) { if(A[p] == 0) { A[++k]=2; A[++j]=1; A[++i]=0; } else if (A[p] == 1) { A[++k]=2; A[++j]=1; } else if (A[p] == 2) { A[++k]=2; } } }
相关文章推荐
- Python数据类型(元组、列表、字符串、字典)
- 使用Jmeter进行http接口性能测试
- PHP 环境安装
- JAVA版微信支付V3-完全版
- objective-C 枚举型和BOOL型
- 重写Redis字典
- AndroidStudio导入第三方类库
- zzuli OJ 1125: 上三角矩阵的判断
- cocos2d-x游戏开发之烟花粒子效果
- Qt之Q_OBJECT 宏定义
- dequeueReusableCellWithIdentifier: forIndexPath: 获取cell
- hadoop 2.4.1 伪分布部署
- Android网络服务发现(NSD)协议的使用
- Single Number I II III
- Objective-C_语言 练习题2
- java lock
- CentOS 添加常用 yum 源
- 107,Protocol在代理设计模式中应用
- project professional 2010重新输入密钥
- [leetcode] 234. Palindrome Linked List 解题报告