码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode 75 Sort Colors(颜色排序)

时间:2017-07-31 20:05:09      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:represent   pen   white   .text   实现   opera   rip   length   str   

翻译

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

在这里,我们将使用数字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);
    }              
}

LeetCode 75 Sort Colors(颜色排序)

标签:represent   pen   white   .text   实现   opera   rip   length   str   

原文地址:http://www.cnblogs.com/jhcelue/p/7264951.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!