給定一個包含紅色、白色和藍色,一共 n 個元素的數組,原地對它們進行排序,使得相同顏色的元素相鄰,并按照紅色、白色、藍色順序排列。
此題中,我們使用整數 0、 1 和 2 分別表示紅色、白色和藍色。
思路:將紅色和藍色排在兩邊,中間剩的就是白色了;另一種是遍歷一遍數組,統計各種顏色數量后輸出,但是沒有前者快
class Solution {public void sortColors(int[] nums) {int red = 0;int blue = nums.length - 1;for(int i = 0;i<blue+1;i++){if(nums[i] == 0){nums[red++] = 0;}//將藍色部分要置換到前面來,不能像紅色那樣直接覆蓋,因為還沒有遍歷else if(nums[i] == 2){int temp = nums[i];nums[i] = nums[blue];nums[blue--] = temp;i--;}}for(int white = red;white<=blue;white++)//把中間設為白色nums[white] = 1;}
}