【题目】
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。
【扫描两遍的计数排序】
public class Solution { public void sortColors(int[] A) { int i, r, w, b; r = w = b = 0; for (i = 0; i < A.length; i++) { if (A[i] == 0) r++; else if (A[i] == 1) w++; else b++; } for (i = 0; i < A.length; i++) { if (i < r) A[i] = 0; else if (i < r + w) A[i] = 1; else A[i] = 2; } } }
【扫描一遍,双向遍历】
从数组两端向中间遍历,前面放0,后面放2,。把前面出现的2放到后面,后面出现的0放到前面,这样中间剩下的就是1。
用i, j两个指针遍历数组,r, b两个变量记录当前出现0和2的个数,也即放0和2的位置指针。
public class Solution { public void swap(int[] A, int a, int b) { int tmp = A[a]; A[a] = A[b]; A[b] = tmp; } public void sortColors(int[] A) { int len = A.length; int i, j, r, w, b; i = 0; j = len - 1; r = b = 0; while (i <= j) { if (A[i] == 0) { swap(A, i, r); i++; r++; continue; } if (A[j] == 2) { swap(A, j, len-1-b); j--; b++; continue; } if (A[j] == 0) { swap(A, i, j); continue; } if (A[i] == 2) { swap(A, i, j); continue; } //如果上述任何情况都不满足,那么只有下面一种可能 //if (A[i] == 1 && A[j] == 1) { i++; j--; //} } } }
【扫描一遍,单向遍历】
后来发现,从一个方向遍历更简单,因为双向遍历两个指针容易搞混,一个指针逻辑更清楚。
public class Solution { public void swap(int[] A, int a, int b) { int tmp = A[a]; A[a] = A[b]; A[b] = tmp; } public void sortColors(int[] A) { int len = A.length; int i, r = 0, b = 0; for (i = 0; i < len-b; i++) { if (A[i] == 0) { swap(A, i, r); r++; } else if (A[i] == 2) { swap(A, i, len-1-b); b++; i--; //后面交换过来的元素也要进行判断 } } } }