Sort Colors

本文介绍了一种将数组中0、1、2三种颜色按顺序排列的算法。通过统计每种颜色的数量,并利用两次交换操作实现排序。

* Sort Colors*
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.

题目的要求就是把一个0,1,2散乱的数组,变成先都是0,再到都是1,再到都是2的数组。
我采用的方式是,统计出0和1的个数,分别为N0,N1。数组总体个数是N,把[0,N0)中的非0元素和[N0,N)中的0元素对调。再把[N0,N0+N1)中的非1元素和[N0+N1,N)中的1元素对调。

class Solution {
public:
    void sortColors(vector<int>& nums) {
        int num_0=0;
        int num_1=0;
        for(int i=0;i<nums.size();i++){    
            if(nums[i]==0)
                num_0++;
            if(nums[i]==1)
                num_1++;
        }
        int j=num_0;
        for(int i=0;i<num_0;i++){
            if(nums[i]!=0){
                for(;j<nums.size();j++){
                    if(nums[j]==0){
                        int temp=nums[j];
                        nums[j]=nums[i];
                        nums[i]=temp;
                        break;
                    }
                }
            }
        }

        j=num_0+num_1;
        for(int i=num_0;i<num_0+num_1;i++){
            if(nums[i]!=1){
                for(;j<nums.size();j++){
                    if(nums[j]==1){
                        int temp=nums[j];
                        nums[j]=nums[i];
                        nums[i]=temp;
                        break;
                    }
                }
            }
        }

    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值