題目:
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.
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?
題解:
這道題就是運用指標來解決了,可以說叫3指標吧。
一個指標notred從左開始找,指向第一個不是0(紅色)的位置;一個指標notblue從右開始往左找,指向第一個不是2(藍色)的位置。
然後另一個新的指標i指向notred指向的位置,往後遍歷,遍歷到notred的位置。
這途中需要判斷:
當i指向的位置等於0的時候,說明是紅色,把他交換到notred指向的位置,然後notred++,i++。
當i指向的位置等於2的時候,說明是藍色,把他交換到notblue指向的位置,然後notred--。
當i指向的位置等於1的時候,說明是白色,不需要交換,i++即可。
程式碼如下:
2 int tmp = A[i];
3 A[i]=A[j];
4 A[j]=tmp;
5 }
6
7 public static void sortColors(int A[]) {
8 if(A == null || A.length==0)
9 return;
10
11 int notred=0;
12 int notblue=A.length-1;
13
14 while (notred<A.length&&A[notred]==0)
15 notred++;
16
17 while (notblue>=0&&A[notblue]==2)
18 notblue--;
19
20 int i=notred;
21 while (i<=notblue){
22 if (A[i]==0) {
23 swap(A,i,notred);
24 notred++;
25 i++;
26 }else if (A[i]==2) {
27 swap(A,i,notblue);
28 notblue--;
29 }else
30 i++;
31 }
32 }