码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Sort Colors

时间:2014-11-12 16:21:04      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   for   

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?

 
Solution 1:
 1 public class Solution {
 2     public void sortColors(int[] A) {
 3       if(A.length<=1)
 4             return;
 5         int iRed=0,iBlue=A.length-1;
 6         int i=0;
 7         while(i<=iBlue){
 8             if(A[i]==0){
 9                 int temp=A[iRed];
10                 A[iRed]=A[i];
11                 A[i]=temp;
12                 iRed++;
13                 i++;   //cannot be less than iRed 
14             }else if(A[i]==2){
15                 int temp=A[iBlue];
16                 A[iBlue]=A[i];
17                 A[i]=temp;
18                 iBlue--;
19             }else{
20                 i++;
21             }
22         }
23 }
24 }

Solution 2:

 1 public class Solution {
 2     public void sortColors(int[] A) {
 3         int i=-1;   //pointer for 0s
 4         int j=-1;   //pointer for 1s
 5         int k=-1;   //pointer for 2s
 6         for(int m=0;m<A.length;++m){
 7             if(A[m]==0){
 8                 A[++k]=2;
 9                 A[++j]=1;
10                 A[++i]=0;
11             }else if(A[m]==1){
12                 A[++k]=2;
13                 A[++j]=1;
14             }else{
15                 A[++k]=2;
16             }
17         }
18     }
19 }

 i,j,k三个指针分别指向0,1,2段的结尾处。

[Leetcode] Sort Colors

标签:style   blog   http   io   color   ar   os   sp   for   

原文地址:http://www.cnblogs.com/Phoebe815/p/4092522.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!