leetCode75:Sort Colors

来源:互联网 发布:淘宝手机店铺免费模板 编辑:程序博客网 时间:2024/06/07 16:59


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++;    }    }


0 0
原创粉丝点击