75. Sort Colors--数组排序

来源:互联网 发布:mac画流程图 编辑:程序博客网 时间:2024/05/22 13:34

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.

Note:
You are not suppose to use the library's sort function for this problem.

用0,1,2,分别代表红色,白色和蓝色,按照红白蓝的顺序排序,并且相同的颜色要相邻,所以这道题是对一个含有0,1,2三个元素的数组排序即可,但是不能调用排序函数Arrays.sort(),所以需要扫描两遍数组,第一次计数,记录每个数字出现的次数,第二次给数组赋值,代码如下:

if(nums.length<2){return;}    int count0=0,count1=0,count2=0;        for(int i=0;i<nums.length;i++){        if(nums[i]==0){count0++;}        if(nums[i]==1){count1++;}        if(nums[i]==2){count2++;}                }               for(int j = 0;j<count0;j++){        nums[j]=0;        }        for(int k = 0;k<count1;k++){        nums[k+count0]=1;        }        for(int l=0;l<count2;l++){        nums[l+count0+count1]=2;        }
但是这种写法效率很低==在网上找了另一种方法,直接平移,当数组中的数字为0,时,数组中的0,1,2都向后平移一位,当数字为1时,1和2向后移动一位,数字为2时,仅2向后移一位,虽然这种方法效率也不高==但是只对数组扫描了一遍,代码如下:

int len = nums.length;int j=-1,k=-1,n=-1;for(int i=0;i<len;i++){if(nums[i]==0){nums[++n]=2;nums[++k]=1;nums[++j]=0;}else if(nums[i]==1){nums[++n]=2;nums[++k]=1;}else{nums[++n]=2;}}



原创粉丝点击