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?

 
用i记录0应该放的位置,j记录2应该放的位置。
cur从0到j扫描,
遇到0,放在i位置,i后移;
遇到2,放在j位置,j前移;
遇到1,cur后移。
扫描一遍得到排好序的数组。
时间O(n)且一次扫描,空间O(1),满足要求。
这么做的前提是,拿到一个值,就知道它应该放在哪儿。(这点和快排的根据pivot交换元素有点像)
 
 1 public class Solution {
 2     public void sortColors(int[] A) {
 3         int len = A.length;
 4         int redIndex = 0, blueIndex = len -1;
 5         int i = 0;
 6         while(i< blueIndex+1){
 7             if(A[i] == 0){
 8                 swap(A,i, redIndex);
 9                 redIndex++;
10                 i++;
11             }else if(A[i] == 2){
12                 swap(A, i, blueIndex);
13                 blueIndex--;
14             }else{
15                 i++;
16             }
17         }
18     }
19     
20     private void swap(int[] A, int i, int j){
21         int temp = A[i];
22         A[i] = A[j];
23         A[j] =temp;
24     }
25 }
View Code
原文地址:https://www.cnblogs.com/RazerLu/p/3545252.html