顏色分類
1 題目地址
https://leetcode-cn.com/problems/sort-colors/
2 題目描述
給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,並按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
注意:
不能使用代碼庫中的排序函數來解決這道題。
示例:
輸入: [2,0,2,1,1,0]
輸出: [0,0,1,1,2,2]
3 思路
雙指針,把0放到左邊,把2放到右邊
/**
* 雙指針把0移動到左邊,把2移動到右邊
*/
public static void sortColors(int[] nums) {
int leftIndex = 0;
int rightIndex = nums.length - 1;
int index = 0;
while (index <= rightIndex) {
if (nums[index] == 0) {
swap(nums, leftIndex++, index++);
} else if (nums[index] == 2) {
swap(nums, index, rightIndex--);
} else {
index++;
}
}
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}