leetCode75: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.



问题需求:

以0,1,2分别代表红白蓝三类颜色,将数组里相同颜色元素放在一起,说白了就将数组的0,1,2按照非递减的顺序放一起。

问题分析:

只要分别计算数组里面红白蓝的个数,然后重新将数组写一遍即可。

示例代码

void sortColors(int* nums, int numsSize) {
    int p = 0,p1 = 0,p2 = 0,p3 = 0;
    int red = 0,blue = 0,white = 0;//记录数组里面红白蓝的个数
    if(numsSize==0||numsSize==1) return;//边界
    //计算数组里面红白蓝得个数
    while(p<numsSize){
        if(nums[p]==0) red++;
        else if(nums[p]==2) blue++;
        else if(nums[p]==1) white++;
        p++;
    }
    p = 0;
    //重新写入这个数组
    while(p<numsSize){
        if(p1<red){
            nums[p] = 0;
            p1++;
        }
        else if(p2<white){
            nums[p] = 1;
            p2++;
        }
        else if(p3<blue){
            nums[p] = 2;
            p3++;
        }
        p++;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值