题目: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.
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 an one-pass algorithm using only constant space?
解析1:我们可以利用快速排序的 partition 算法,时间复杂度为 O(n),空间复杂度 O(1),代码如下:
// 利用快速排序的 partition 算法
// 时间复杂度 O(n),空间复杂度 O(1)
class Solution {
public:
void sortColors(vector<int>& nums) {
if (nums.size() <= 1) return;
int i = -1;
for (int j = 0; j < nums.size(); ++j)
if (nums[j] == 0) {
++i;
swap(nums[i], nums[j]);
}
for (int j = i + 1; j < nums.size(); ++j)
if (nums[j] == 1) {
++i;
swap(nums[i], nums[j]);
}
}
};
解析2:利用计数排序的方法,时间复杂度为 O(n),空间复杂度为 O(1)
class Solution {
public:
void sortColors(vector<int>& nums) {
// 记录每个颜色出现的次数
int counts[3] = { 0 };
for (int i = 0; i < nums.size(); ++i)
++counts[nums[i]];
for (int i = 0, index = 0; i < 3; ++i)
for (int j = 0; j < counts[i]; ++j)
nums[index++] = i;
}
};