LeetCode筆記——75顏色分類
題目:
給定一個包含紅色、白色和藍色,一共 n 個元素的陣列,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
注意: 不能使用程式碼庫中的排序函式來解決這道題。
示例:
輸入: [2,0,2,1,1,0] 輸出: [0,0,1,1,2,2]
進階:
- 一個直觀的解決方案是使用計數排序的兩趟掃描演算法。 首先,迭代計算出0、1 和 2 元素的個數,然後按照0、1、2的排序,重寫當前陣列。
- 你能想出一個僅使用常數空間的一趟掃描演算法嗎?
在以下程式碼中使用了三個指標,遍歷陣列一遍得到最終的結果。指標redIndex,blueIndex一個指向1元素的開頭,一個指向1元素的結尾,另一個指標index用來遍歷整個陣列。如果index指向的是紅色,則交換index,redIndex兩個值,並且兩指標加1;若指向藍色,則交換index,blueIndex兩數的值,只減小blueIndex的值,不增加index的值。但是這塊我有點看不懂。。。原文中說總能保證交換過來的元素是1。試了幾個例子之後明白了,redIndex交換出去的永遠是1,,但是blueIndex交換出去的可能是2還需要判斷。
程式碼:
class Solution { public void sortColors(int[] nums) { if (nums.length == 0) return; int n=nums.length; int redIndex = 0; //points to the first one that may be not red int blueIndex = n - 1; //points to the first one that may be not blue int index = 0; while (index <= blueIndex) { if (nums[index] == 0) { //swap(nums[index], nums[redIndex]); int temp1; temp1=nums[redIndex]; nums[redIndex]=nums[index]; nums[index]=temp1; redIndex++; index++; //cannot be less than redIndex } else if (nums[index] == 2) { //swap(nums[index], nums[blueIndex]); int temp2; temp2=nums[blueIndex]; nums[blueIndex]=nums[index]; nums[index]=temp2; blueIndex--; } else index++; }
} }
執行最快的程式碼:
與上面的思路一致
class Solution { public void sortColors(int[] nums) { int low =0; int hight = nums.length-1; int index = 0; while (index<=hight){ if (nums[index] ==2){ int temp = nums[hight]; nums[hight] = nums[index]; nums[index]=temp; hight--; }else if (nums[index] ==0){ int temp = nums[low]; nums[low] = nums[index]; nums[index]=temp; low++; index++; }else {index++;} } }