Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
題意:有一個(gè)包含紅白藍(lán)三色的數(shù)組,分別用0、1、2表示三種顏色,對(duì)這個(gè)顏色數(shù)組按照紅白藍(lán)的順序排序。不允許用庫函數(shù)。
思路:這道題想到了之前學(xué)過的雙指針方法,用left和right兩個(gè)指針記錄當(dāng)前左邊紅色和右邊藍(lán)色已經(jīng)排序好的位置,用一個(gè)游標(biāo)來遍歷數(shù)組。
如果游標(biāo)處的顏色是0,并且游標(biāo)大于left,則交換游標(biāo)和left,left右移;如果游標(biāo)的顏色是2,并且游標(biāo)小于right,交換游標(biāo)和right,right左移;如果游標(biāo)當(dāng)前是1、或者是0并且小于等于left、或者是2并且大于等于right,則游標(biāo)右移。
public void sortColors(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
int left = 0, right = nums.length - 1, cur = 0;
while (cur <= right) {
if (cur > left && nums[cur] == 0) {
int tmp = nums[left];
nums[left] = nums[cur];
nums[cur] = tmp;
left++;
}
if (cur < right && nums[cur] == 2) {
int tmp = nums[right];
nums[right] = nums[cur];
nums[cur] = tmp;
right--;
}
if (nums[cur] == 1 || (nums[cur] == 0 && cur <= left) || (nums[cur] == 2 && cur >= right)) {
cur++;
}
}
}