給定一個包含紅色、白色、藍色這三個顏色對象的數組,對它們進行排序以使相同的顏色變成相鄰的,其順序是紅色、白色、藍色。
在這裡,我們將使用數字0、1和2分別來代表紅色、白色和藍色。
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.
看到這道題,立馬就想到了range-for,可能這種方法有些投機吧,不過確實很容易就實現了。
void sortColors(vector& nums) {
vector v0, v1, v2;
for (auto n : nums) {
switch (n)
{
case 0:
v0.push_back(n);
break;
case 1:
v1.push_back(1);
break;
case 2:
v2.push_back(2);
break;
default:
break;
}
}
nums.erase(nums.begin(), nums.end());
for (auto a0 : v0) {
nums.push_back(a0);
}
for (auto a1 : v1) {
nums.push_back(a1);
}
for (auto a2 : v2) {
nums.push_back(a2);
}
}