首页 > 代码库 > Leetcode: Sort Colors

Leetcode: 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.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?

难度:naive做法60,计数排序

 1 public class Solution { 2     public void sortColors(int[] A) { 3         if (A == null || A.length == 0) return;  4         int[] colornum = new int[3]; 5         for (int elem : A) { 6             if (elem == 0) colornum[0]++; 7             if (elem == 1) colornum[1]++; 8             if (elem == 2) colornum[2]++; 9         }10         for (int i=0; i<colornum[0]; i++) {11             A[i] = 0;12         }13         for (int i=colornum[0]; i<colornum[0]+colornum[1]; i++) {14             A[i] = 1;15         }16         for (int i=colornum[0]+colornum[1]; i<A.length; i++) {17             A[i] = 2;18         }19     }20 }

我们考虑怎么用一次扫描来解决。

网上有一个做法,还没怎么看懂。

 1 public void sortColors(int[] A) { 2     if(A==null || A.length==0) 3         return; 4     int idx0 = 0; 5     int idx1 = 0; 6     for(int i=0;i<A.length;i++) 7     { 8         if(A[i]==0) 9         {10             A[i] = 2;11             A[idx1++] = 1;12             A[idx0++] = 0;13         }14         else if(A[i]==1)15         {16             A[i] = 2;17             A[idx1++] = 1;18         }19     }20 }

 

Leetcode: Sort Colors