题目描述:
Given an array with n objects colored red, white or blue, sort them in-place 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.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
- A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0’s, 1’s, and 2’s, then overwrite array with total number of 0’s, then 1’s and followed by 2’s. - Could you come up with a one-pass algorithm using only constant space?
给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同颜色的元素相邻,并按照红色、白色、蓝色顺序排列。
此题中,我们使用整数 0、 1 和 2 分别表示红色、白色和蓝色。
注意:
不能使用代码库中的排序函数来解决这道题。
示例:
输入: [2,0,2,1,1,0]
输出: [0,0,1,1,2,2]
进阶:
- 一个直观的解决方案是使用计数排序的两趟扫描算法。
首先,迭代计算出0、1 和 2 元素的个数,然后按照0、1、2的排序,重写当前数组。 - 你能想出一个仅使用常数空间的一趟扫描算法吗?
思路:
解法一(Count Sort):
数组的元素一共有 3 种,要求原地进行排序,最简单的方法就是使用计数排序。
public void sortColors(int[] nums) {
int a = 0, b = 0, c = 0;
for (int n : nums) {
if (n == 0) a++;
if (n == 1) b++;
if (n == 2) c++;
}
int i = 0;
for (; i < a; i++) nums[i] = 0;
for (; i < b; i++) nums[i] = 1;
for (; i < c; i++) nums[i] = 2;
}
时间复杂度:
。
空间复杂度:
。
解法二(Three-Way QuickSort):
因为题目只给了三种元素,那么正好与三路快速排序的思路相吻合。三路快排即将等于枢纽元的元素放在中间位置,小于的放在前面,大于的放在后面,仅需遍历一遍后即符合题意要求。
public void sortColors(int[] nums) {
int left = -1; // nums[0...left]
int right = nums.length; // nums[right...n-1]
for (int i = 0 ;i < right ; ) {
if (nums[i] == 1) // 枢纽元
i ++;
else if (nums[i] == 2)
swap(nums, i, --right);
else {
assert nums[i] == 0;
swap(nums, i++, ++left);
}
}
}
public void swap(int[] arr, int a, int b) {
if (a != b) {
arr[a] ^= arr[b];
arr[b] ^= arr[a];
arr[a] ^= arr[b];
}
}
时间复杂度:
。
空间复杂度:
。
解法三(Two-Pass):
与三路快排类似,主要也是通过交换来完成排序,将 0 往前交换,将 2 往后交换。
public void sortColors(int[] nums) {
// [0...zero] [second...n-1]
int second = nums.length - 1, zero = 0;
for (int i = 0; i <= second; i++) {
while (nums[i] == 2 && i < second) swap(nums, i, second--);
while (nums[i] == 0 && i > zero) swap(nums, i, zero++);
}
}
代码都是可以直接运行的,希望能帮到一些人,如果文章里有说得不对的地方还请前辈指正~
参考:
75. Sort Colors——billyzhang
Four different solutions
Share my at most two-pass constant space 10-line solution