[LeetCode99]Sort Colors
来源:互联网 发布:数控车床g76螺纹编程 编辑:程序博客网 时间:2024/05/21 17:08
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?
Analysis:
一开始想到的就是计数排序,但是计数排序需要两边扫描,第一遍统计红,白,蓝的数目,第二遍生成新数组。
考虑到题目要求one pass。这就意味着类似于链表的双指针问题,这里也要track两个index,一个是red的index,一个是blue的index,两边往中间走。
i从0到blue index扫描,
遇到0,放在red index位置,red index后移;
遇到2,放在blue index位置,blue index前移;
遇到1,i后移。
扫描一遍得到排好序的数组。时间O(n),空间O(1).
Java
public void sortColors(int[] A) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. int redSt = 0, blueSt = A.length-1; int i=0; while(i<blueSt+1) { if(A[i]==0){ int temp = A[i]; A[i] = A[redSt]; A[redSt] = temp; redSt++; i++; continue; } if(A[i]==2){ int temp = A[i]; A[i] = A[blueSt]; A[blueSt] = temp; blueSt--; continue; } i++; }}
c++
void sortColors(int A[], int n) { int red = 0; int blue = n-1; while(A[red]==0) red++; while(A[blue]==2) blue--; int i = red; while(i<=blue){ if(A[i]==0){ swap(A[i],A[red]); red++; i++; }else if(A[i]==2){ swap(A[i],A[blue]); blue--; }else{ i++; } } }
- [LeetCode99]Sort Colors
- leetcode99
- 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
- 丫头今天又苦于口语
- 的符号的发货房合法化房合法化的人员和日语人员也容易热叶荣添
- 股份有一块发邮件的共同山乌
- 55_leetcode_remove Duplicates from Sorted List
- 河南高考替考事件23人被调查控制 9人承认涉案
- [LeetCode99]Sort Colors
- 如何彻底隐藏iOS7应用的status bar
- 56_leetcode_Remove Duplicates from Sorted Lists II
- 敬佛了附件礼物了报告分为拉克服了
- Autofac介绍
- 找到属于自己的路——leo鉴书62
- Oracle中as关键字作为别名使用时的用法详解
- 57_leetcode_partition List
- 使用Fiddler提高前端工作效率 (介绍篇)