【leetcode】75. Sort ColorsD

Difficulty:Medium

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.


解题思路:

在第一次尝试的时候,使用了对数组直接进行盲目排序的方式,用冒泡排序,时间复杂度为O(n^2),结果超时,代码如下,不在赘述方法

代码如下:

void sortColors(int* nums, int numsSize) {
    int n=numsSize;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n-1;j++)
        {
            if(nums[j]>nums[j+1])
            {
                int temp=nums[j];
                nums[j]=nums[j+1];
                nums[j+1]=temp;
            }
        }
    }
}
之后考虑到了本题具有的特性,题目中给出的数字很有特点,只有0,1,2数字,这样就需要考虑比较有特点的方法。

所以采用了一种平推计数的方法,分别中采用3个量计算0,1,2数字当前更新的位置,假如当前位置arr[i]对应的数字是0,那么给0,1,2的当前位置都赋值自己的值,并且给当前0,1,2位置的记录都增加1,如果arr[i]为1,那么给1,2的当前位置都赋值自己的值,并且给当前1,2位置的记录都增加1,arr[i]=2时,只给2对应位置的值赋值为2,并且增加2的指针位置,这样,如果每次更新位置的时候,如果是0,每次都将0的总值增加了1,并且前面的是数字都是0,而每次的0都会覆盖因为之前变化引起的值得变化,对于其他的值也是相同的

void sortColors(int* nums, int numsSize) {
    int x=-1;
    int y=-1;
    int z=-1;
    int n=numsSize;
    for(int i=0;i<n;i++)
    {
        if(nums[i]==0)
        {
            nums[++x]=2;
            nums[++y]=1;
            nums[++z]=0;
        }
        else if(nums[i]==1)
        {
            nums[++x]=2;
            nums[++y]=1;
            
        }
        else nums[++x]=2;
    }
}

代码如下:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值