描述
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.
For example: [1,2,1,1,0,0,2,1,0]
思路
- 思路1:快速排序的变体,见《算法-第四版》P189
- 思路2:桶排序
- 更正一下思路一:这道题其实可能可以不用递归调用的,因为只有三个数,一次运行后,有可能就会对的,但是必须保证切分点是中间值,如原始输入为[1,0,2]可以Accept,[0,1,2]就不能过。所以还是需要递归。
实现
快速排序
class Solution {
public void exch(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public void sortQuickThreeWay(int[] nums, int lo, int hi){
if (hi <= lo)
return;
int less = lo;
int i = lo + 1;
int great = hi;
int v = nums[lo];
while(i <= great){
if (nums[i] < v) exch(nums, less++, i++);
else if (nums[i] > v) exch(nums, i, great--);
else i++;
}
sortQuickThreeWay(nums, lo, less-1);
sortQuickThreeWay(nums, great+1, hi);
}
public void sortColors(int[] nums) {
sortQuickThreeWay(nums, 0, nums.length-1);
}
}
桶排序
class Solution {
public void sortColors(int[] nums) {
if (nums.length <= 1){
return;
}
int[] states = new int[3];
for (int i = 0; i < nums.length; i++){
states[nums[i]]++;
}
for (int j = 1; j < 3; j++){
states[j] += states[j-1];
}
Arrays.fill(nums, 0, states[0], 0);
Arrays.fill(nums, states[0], states[1], 1);
Arrays.fill(nums, states[1], states[2], 2);
}
}
本文介绍了一种特殊的排序问题——三色排序,即给定一个包含红色、白色和蓝色三种颜色的数组,要求将它们按红、白、蓝的顺序进行排序。通过两种不同的算法实现:一种是快速排序的变体,另一种是桶排序。

被折叠的 条评论
为什么被折叠?



