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.算法
給定一個對象數組,對象是紅色,白色和藍色,對顏色進行排序,紅,白,藍。
使用0,1,2分別表明紅,白,藍。
注意:不能使用庫函數進行排序。數組
對數組進行掃描,計錄1的個數和整個數組的和。掃描完後能夠得出1的數目t,2的數目(sum-t)/2,最後能夠得出0的數目,這樣子根據0,1,2的數目再對數組進行設置值。函數
算法實現類this
public class Solution { public void sortColors(int[] A) { if (A == null) { return; } int count = 0; // 統計1的個數 int sum = 0; // 統計數組的和 for (int i : A) { if (i == 1) { count++; } sum += i; } sum = (sum - count) /2; // 計算2的數目 count = A.length - count - sum; // 1開始出現的位置 sum = A.length - sum; // 2開始出現的位置 for (int i = 0; i < count; i++) { A[i] = 0; } for (int i = count; i < sum; i++) { A[i] = 1; } for (int i = sum; i < A.length; i++) { A[i] = 2; } } }