Sort Colors (two ways)

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.

(不能使用Arrays.sort(A),其实我有偷着用了一下,只需要写一行代码调用一下,但是运行时间也并没有很短啦)

/*方法一 :新建一个数组newA[],对A进行遍历,当元素为0,存入新数组头部,元素为2则存入新数组尾部,
最后将新数组中间部分都置为1,时间复杂度为O(n),runtime = 218ms*/
public class Solution {   
	public void sortColors(int[] A) {
    	int l = 0;
    	int i = 0;
    	int len = A.length;
    	int h = len - 1; 
    	int newA[] = new int[len];
    	while (i < len){
    		if (A[i] == 0){
    			newA[l ++] = A[i];
    		}
    		if (A[i] == 2){
    			newA[h --] = A[i];
    		}
    		i ++;
    	}
    	while (l <= h){
    		newA[l] = 1;
    		l ++;
    	}
    	A = newA;
    	for (i = 0; i < len; i ++){
    	    //A[i] = newA[i];
    		System.out.print(A[i] + " ");
    	}
    }
}

/*方法二:新建一个数组count[],对A进行遍历,将0,1,2分别出现的次数存入新数组的0,1,2位置,
 * 然后根据count值对A重新赋值,时间复杂度为O(n),runtime = 197ms */
public class Solution {
	 public void sortColors(int[] A) {
			int count[] = new int[3];
			int i = 0;
			for(i = 0; i < A.length; i ++) {
				count[A[i]]++;
			}
			int j = 0;
			for (i = 0; i < 3; i++) {
				while (count[i] > 0){
					A[j ++] = i;
					count[i] --;
				}
			}
		}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值