一、问题描述
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.
二、问题分析
这里有几种解决方案:
1.计数,不过需要two pass
2.排序,可以自己写快排
3.双指针法 或者叫三指针
一个指针notred从左开始找,指向第一个不是0(红色)的位置;一个指针notblue从右开始往左找,指向第一个不是2(蓝色)的位置。
然后另一个新的指针i指向notred指向的位置,往后遍历,遍历到notblue的位置。
这途中需要判断:
当i指向的位置等于0的时候,说明是红色,把他交换到notred指向的位置,然后notred++,i++。
当i指向的位置等于2的时候,说明是蓝色,把他交换到notblue指向的位置,然后notred--。
当i指向的位置等于1的时候,说明是白色,不需要交换,i++即可。
三、Java AC代码
1.自己写快排
public void qSort(int[] nums, int left, int right) {
int low = left, high = right;
if (low >= high) {
return;
}
int key = nums[low];
while (low < high) {
while (low < high && nums[high] >= key)
high--;
nums[low] = nums[high];
while (low < high && nums[low] <= key)
low++;
nums[high] = nums[low];
}
nums[low] = key;
qSort(nums, left, low - 1);
qSort(nums, low + 1, right);
}
public void sortColors(int[] nums) {
qSort(nums, 0, nums.length-1);
}
2.双指针
public void sortColors(int[] nums) {
int notRed = 0;
int notBlue = nums.length-1;
while(notRed<nums.length && nums[notRed]==0) notRed++;
while(notBlue>=0 && nums[notBlue]==2) notBlue--;
int p = notRed;
while(p<=notBlue){
if (nums[p]==2) {
nums[p] = nums[notBlue];
nums[notBlue] = 2;
notBlue--;
}else if (nums[p]==0) {
nums[p] = nums[notRed];
nums[notRed] = 0;
notRed++;
p++;
}else p++;
}
}