声明:原题目转载自LeetCode,解答部分为原创
Problem :
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.
思路:最直观的想法是,遍历一遍容器类nums中的元素,记录“0” “1” “2”各自的数目,再将按“0“-”1“-”2“的顺序拷贝到 清空了的容器类nums中。当然,考虑到本题的意图是重排序,我选择用三个容器类分别存放nums中的”0“ ”1“ ”2“元素,再将三个容器类的元素按顺序拷贝到 清空了的nums 中。
代码如下:
class Solution {
public:
void sortColors(vector<int>& nums) {
vector<int> num_0;
vector<int> num_1;
vector<int> num_2;
for(int i = 0 ; i < nums.size() ; i ++)
{
if(nums[i] == 0)
num_0.push_back(nums[i]);
else if(nums[i] == 1)
num_1.push_back(nums[i]);
else
num_2.push_back(nums[i]);
}
nums.erase(nums.begin(), nums.end());
add(nums, num_0);
add(nums, num_1);
add(nums, num_2);
}
private:
void add(vector<int> & des, vector<int> & s)
{
for(int i = 0 ; i < s.size() ; i ++)
{
des.push_back(s[i]);
}
}
};