Sort Colors
来源:互联网 发布:天猫淘宝棉拖鞋 编辑:程序博客网 时间:2024/05/01 03:20
Sort Colors
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.
两种思路,一种遍历计数,一种三指针交换
class Solution {public: void sortColors(int a[], int n) { int p,i,m; p=0,m=0; for(i=0;i<n;i++) { if(a[i]==0) p++; if(a[i]==1) m++; } for(i=0;i<p;i++) { a[i]=0; } for(;i<p+m;i++) { a[i]=1; } for(;i<n;i++) { a[i]=2; } }};
class Solution {public:void sortColors(int a[], int n) { int i = -1; int j = -1; int k = -1; for(int p = 0; p < n; 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 a[++k] = 2; } }};
class Solution {public: void swap(int a[],int m,int n) { int tem=a[m]; a[m]=a[n]; a[n]=tem; } void sortColors(int a[], int n) { int l,cur,r; l=0,r=n-1,cur=n-1; while(cur>=l) { if(a[cur]==0) { swap(a,cur,l); l++; } else if(a[cur]==2) { swap(a,cur,r); r--; cur--; } else cur--; } }};
0 0
- 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
- C语言基本数据类型的介绍
- [BFUACM]辗转相除法
- 为每位消费者爱车担保200万美金保险,是任性,还是疯了?
- jquery取kindeditor插件的textarea的值
- 【Github教程】史上最全github使用方法:github入门到精通
- Sort Colors
- 【基础练习】【模拟】Uva489 - Hangman Judge题解
- ⑩--Foundation框架基础
- 20150117学习总结
- E - 1sting (递推+大数加法)
- 32位汇编语言学习笔记(45)--测试简单文件操作接口(完)
- Linux Barrier IO
- HDU1864 01背包
- 什么时候使用存储过程比较适合?