Middle-题目28:75. 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三个数字,对其排序。
题目分析:
1. 朴素解法:既然是排序,调用Java的API即可。
2. 计数排序:先扫描一遍数组,统计有多少0,多少1,多少2,然后再扫描一遍数组,按0,1,2的个数分别填充数组。
3. 交换排序:从0开始记录红色和白色的插入位置,扫描数组,如果扫到当前位置是1,则与1应插入的位置交换,如果扫到当前位置是0,则先与1插入的位置交换,再与0插入的位置交换。(因为换到0的位置以后,1的位置也向后移动了)
源码:(language:c)
方法1略。
方法2:

void sortColors(int* nums, int numsSize) {
    int red=0,white=0,blue=0;
    for(int i = 0;i<numsSize;i++) {
        if(nums[i] == 0)
            red++;
        else if(nums[i] == 1)
            white++;
        else
            blue++;
    }
    for(int i=0;i < numsSize;i++) {
        if(red > 0) {
            red--;
            nums[i]=0;
        }
        else if(white > 0) {
            white--;
            nums[i]=1;
        }
        else
            nums[i]=2;
    }
}

方法3:

void sortColors(int* nums, int numsSize) {
    int Insert_Red=0,Insert_White=0;
    for(int i=0;i<numsSize;i++) {
      if(nums[i]==1) {    
           nums[i]=nums[Insert_White];
           nums[Insert_White++]=1;
      }
      else if(nums[i]==0) {   
           nums[i]=nums[Insert_White];
           nums[Insert_White++]=nums[Insert_Red];
           nums[Insert_Red++]=0;
      }

    }
}

成绩:
方法1:1ms,beats 3.63%,众数1ms,75.47%
方法2:0ms,beats 2.63%,众数0ms,97.37%
方法3:2ms,beats 2.63%
Cmershen的碎碎念:
方法2和方法3的时间复杂度都是O(n),但方法2扫了两遍数组,方法3扫了一遍,但多次提交都是方法2时间短。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值