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.

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值