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时间短。

你可能感兴趣的:(Middle-题目28:75. Sort Colors)