題目
給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
注意:
不能使用代碼庫中的排序函數來解決這道題。
示例:
輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
進階:
一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前數組。
你能想出一個僅使用常數空間的一趟掃描算法嗎?
分析
這道題目考察的實際上是三路快排的 partition 操作,三路快排處理包含重複元素的數組速度更快。
引入變量 ,定義循環不變量:
- 中的數都是0.
- 中的數都是1.
- 是未知區域.
- 中的數都是2.
圖解:
代碼
class Solution {
public void sortColors(int[] nums) {
int lt = 0, gt = nums.length - 1;
int i = 0;
while (i <= gt) {
if (nums[i] < 1) exch(nums, lt++, i++);
else if (nums[i] > 1) exch(nums, i, gt--);
else i++;
}
}
private void exch(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}