【LeetCode】Sort Colors
来源:互联网 发布:淘宝好评怎么删除图片 编辑:程序博客网 时间:2024/05/01 20:28
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?
class Solution {public: void sortColors(int A[], int n) { int i=0; int flag1=n-1,flag2=n-1; while(i<=flag1){ if(A[i]==2){ int tmp=A[i]; A[i]=A[flag2]; A[flag2]=tmp; flag2--; if(flag2<flag1)flag1=flag2; }else if(A[i]==1){ int tmp=A[i]; A[i]=A[flag1]; A[flag1]=tmp; flag1--; }else{ i++; } } } };
0 0
- LeetCode: Sort Colors
- LeetCode Sort Colors
- LeetCode : Sort Colors
- leetcode 77: Sort Colors
- Leetcode 75 Sort Colors
- leetcode 101: Sort Colors
- [LeetCode]Sort Colors
- [leetcode]Sort Colors
- LeetCode-Sort Colors
- [leetcode] Sort Colors
- [LeetCode] Sort Colors
- [leetCode] Sort Colors
- LeetCode - Sort Colors
- leetcode:Sort Colors
- LeetCode | Sort Colors
- 【LeetCode】Sort Colors
- Leetcode: Sort Colors
- [LeetCode] Sort Colors
- 8种web监听器详解
- Android 软件测试日志文件抓取
- OpenCV自带的CamShift算法解读
- Servlet容器的分类之我的学习
- c++标准库容器使用概览
- 【LeetCode】Sort Colors
- 隐藏或者显示MacBook 里的隐藏文件
- hdu 4770 Lights Against Dudely
- 坐标转换收集的小资料
- 查询一个数据集中的第一条数据
- scrollTo、scrollBy、getScrollX、getScrollY这4个方法的含义
- java里,当long与上了int
- const map 成员变量初始化例子
- 黑马程序员_Java基础[1]_java特点、Dos命令、标识符、常见关键字