第一种方法(类似radix sort)易想到,第二种类似quicksort的排序,用front和back指针来做。
package Level4;
import java.util.Arrays;
/**
* 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?
*
*/
public class S75 {
public static void main(String[] args) {
int[] A = {0,2,1};
sortColors2(A);
System.out.println(Arrays.toString(A));
}
public static void sortColors(int[] A) {
int red = 0;
int white = 0;
int blue = 0;
for(int i=0; i<A.length; i++){
switch(A[i]){
case 0:
red++;
break;
case 1:
white++;
break;
case 2:
blue++;
break;
}
}
int i;
for(i=0; i<red; i++){
A[i] = 0;
}
for(; i<red+white; i++){
A[i] = 1;
}
for(; i<A.length; i++){
A[i] = 2;
}
}
public static void sortColors2(int[] A) {
// front指针指向数组的前部,back指针指向数组的后部
int front = 0, back = A.length-1;
for(int i=0; i<A.length;){
if(i>back || i<front){ // 始终要保持front<=i<=back
break;
}
switch(A[i]){
case 1: // 跳过1
i++;
break;
case 0: // 与front交换,然后front和i都往后移
swap(A, i, front);
front++;
i++;
break;
case 2: // 与back交换,back往前移
swap(A, i, back);
back--;
break;
}
}
}
private static void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
Again:
public class Solution {
public void sortColors(int[] A) {
int pre=0, post=A.length-1;
int i = 0;
while(i<=post){ // notice this condition!
if(pre > post){
break;
}
if(A[i] == 1){
i++;
continue;
}else if(A[i] == 0){
swap(A, i, pre);
i++;
pre++;
}else if(A[i] == 2){
swap(A, i, post);
post--; // Notice here, we don't increase i
}
}
}
public void swap(int[] A, int i, int j){
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
public void sortColors2(int[] A) {
int len = A.length;
int red=0, white=0, blue=0;
for(int i=0; i<len; i++){
if(A[i] == 0){
red++;
}else if(A[i] == 1){
white++;
}else if(A[i] == 2){
blue++;
}
}
int j;
for(j=0; j<red; j++){
A[j] = 0;
}
for(; j<red+white; j++){
A[j] = 1;
}
for(; j<len; j++){
A[j] = 2;
}
}
}