顏色分類
給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
注意:
不能使用代碼庫中的排序函數來解決這道題。
示例:
輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
進階:
一個直觀的解決方案是使用計數排序的兩趟掃描算法。
首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前數組。
你能想出一個僅使用常數空間的一趟掃描算法嗎?
關鍵點在於,遇到0,與low交換,i++,遇到2,與high交換,i不加。
void sortColors(vector<int>& nums) {
if(nums.size()<=1) return;
int low = 0, high = nums.size() - 1;
while (low < high && nums[low] == 0) low++;
while (low < high && nums[high] == 2) high--;
int i = low;
while(i<=high) {
if (nums[i] == 2) {
swap(nums[i], nums[high]);
high--;
}
else if (nums[i] == 0) {
swap(nums[i], nums[low]);
low++;
i++;
}
else i++;
}
}