LeetCode 75 Sort Colors(颜色排序)

翻译

给定一个包括红色、白色、蓝色这三个颜色对象的数组。对它们进行排序以使同样的颜色变成相邻的,其顺序是红色、白色、蓝色。

在这里,我们将使用数字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。可能这样的方法有些投机吧。只是确实非常easy就实现了。

void sortColors(vector<int>& nums) {
    vector<int> 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);
    }              
}
原文地址:https://www.cnblogs.com/jhcelue/p/7264951.html