[LeetCode] Sort Colors 按颜色排序

本文介绍了一道LeetCode上的题目——按颜色排序数组,要求将红色、白色和蓝色元素按特定顺序排列。禁止使用库的排序功能。解决方案是通过遍历数组,统计各颜色元素数量,然后分别将它们重新填入数组中。
摘要由CSDN通过智能技术生成

声明:原题目转载自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.

Solution:

        思路:最直观的想法是,遍历一遍容器类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]);
        }
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值