給定一個包含紅,白,藍且長度爲 n 的數組,將數組元素進行分類使相同顏色的元素相鄰,並按照紅、白、藍的順序進行排序。
我們可以使用整數 0,1 和 2 分別代表紅,白,藍。
注意事項
不能使用代碼庫中的排序函數來解決這個問題。
排序需要在原數組中進行。
樣例
給你數組 [1, 0, 1, 2], 需要將該數組原地排序爲 [0, 1, 1, 2]。
挑戰
一個相當直接的解決方案是使用計數排序掃描2遍的算法。
首先,迭代數組計算 0,1,2 出現的次數,然後依次用 0,1,2 出現的次數去覆蓋數組。
你否能想出一個僅使用常數級額外空間複雜度且只掃描遍歷一遍數組的算法?
思路:l指向第一個非0的數,r指向倒數第一個非2的數,i指向0時與nums[l]交換,指向2時與nums[r]交換,指向1則繼續向後指。
class Solution {
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
public static void sortColors(int[] nums) {
if(null == nums || nums.length <= 1) return;
int l = 0, r = nums.length-1;
for(int i = 0; i < Math.min(nums.length, r+1);) {
while(i == l && nums[l] == 0) {
i++;
l++;
}
while(nums[r] == 2) {
r--;
}
if(nums[i] == 0) {
nums[i] = nums[l];
nums[l] = 0;
l++;
}else if(nums[i] == 2) {
nums[i] = nums[r];
nums[r] = 2;
r--;
}else {
i++;
}
}
}
}
思路:首先,迭代數組計算 0,1,2 出現的次數,然後依次用 0,1,2 出現的次數去覆蓋數組。
class Solution {
/**
* @param nums: A list of integer which is 0, 1 or 2
* @return: nothing
*/
public void sortColors(int[] nums) {
if(null == nums || nums.length <= 1) return;
int aNum = 0, bNum = 0, cNum = 0;
for(int i = 0; i < nums.length; i++) {
switch(nums[i]) {
case 0:
aNum++;
break;
case 1:
bNum++;
break;
case 2:
cNum++;
break;
default:
return;
}
}
for(int i = 0; i < nums.length; i++) {
if(i < aNum) {
nums[i] = 0;
}else if(i >= aNum && i < aNum+bNum) {
nums[i] = 1;
}else {
nums[i] = 2;
}
}
}
}