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 class Solution {

 2     public void sortColors(int[] A) {

 3         if (A == null) return;

 4         int red = 0;

 5         int white = 0;

 6         int blue = 0;

 7         for (int elem : A) {

 8             if (elem == 0) red++;

 9             else if (elem == 1) white++;

10             else blue++;

11         }

12         int i=0;

13         for (; i<red; i++) {

14             A[i] = 0;

15         }

16         for (; i<red+white; i++) {

17             A[i] = 1;

18         }

19         for (; i<red+white+blue; i++) {

20             A[i] = 2;

21         }

22     }

23 }

 

你可能感兴趣的:(LeetCode)