问题描述
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?
解题思路
该问题给了一个一维数组,数组的每个元素表示一个颜色,共有红、白、蓝,三种颜色,分别用0、1、2来代表,现在要求将数组排序,使得颜色相同的元素在一起,并按照红白蓝的顺序。我们可以这样思考:用三个指针,p1指向1元素的开始,作为0和1的分界点。p2指向1元素的结尾,作为1和2的分界点。p3用来遍历。遍历的时候采取这样的策略:如果p3指向的元素为0,那么交换p3和p1位置的元素。因为刚刚的定义,所以我们总是能够保证交换过来的元素是1,那这样的话我们就p1++,p3++。如果p3指向的元素是2,那么我们交换p2和p3指向的元素,p2–,但是p3不变,因为我们不知道交换过来的是什么元素。这样遍历一边数组之后,就能够得到我们想要的结果了。
代码展示
#include<iostream>
#include<string>
#include<math.h>
#include<vector>
using namespace std;
class Solution {
public:
void sortColors(vector<int>& nums) {
int n = nums.size();
if (n == 0) return;
int redIndex = 0;
int blueIndex = n - 1;
int index = 0;
while (index <= blueIndex)
{
if (nums[index] == 0)
{
swap(nums[index], nums[redIndex]);
redIndex++;
index++;
}
else if (nums[index] == 2)
{
swap(nums[index], nums[blueIndex]);
blueIndex--;
}
else
index++;
}
}
};
int main(){
int n, a;
cout<<"请输入数组大小:";
cin>>n;
vector<int> nums;
for(int i=0;i<n;i++){
cin>>a;
nums.push_back(a);
}
Solution solution;
solution.sortColors(nums);
for(int i=0;i<n;i++){
cout<<nums[i]<<" ";
}
cout<<endl;
return 0;
}
运行结果展示