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?

这道题,其实是对一个整型数组进行排序,这个数组只有0、1、2三个元素,这里提出了一种计数排序的方法
主要是分别记录0、1、2的个数,然后覆盖A数组
如果想cheat可以直接调用系统的Arrays.sort()这个api。明天用快排这些算法实现一下,下面是计数排序的实现
 1 public class Solution {
 2     public void sortColors(int[] A) {
 3         int num_zero = 0;
 4         int num_one = 0;
 5         int num_two = 0;
 6         for(int i = 0; i < A.length; i++){
 7             switch(A[i]){
 8                 case 0:
 9                     num_zero++;
10                     break;
11                 case 1:
12                     num_one++;
13                     break;
14                 case 2:
15                     num_two++;
16                     break;
17             }//switch
18         }//for
19         int point_a = 0;
20         for(int i = 0; i < num_zero; i++){
21             A[point_a++] = 0;
22         }
23         for(int i = 0; i < num_one; i++){
24             A[point_a++] = 1;
25         }
26         for(int i = 0; i < num_two; i++){
27             A[point_a++] = 2;
28         }
29     }
30 }

 

 

posted on 2015-01-11 01:11  luckygxf  阅读(171)  评论(0编辑  收藏  举报

导航