您的位置:首页 > 其它

LeetCode---------------Sort Colors

2015-09-02 11:24 357 查看
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.

程序如下:

public class Solution {

public void sortColors(int[] nums) {

ArrayList<Integer> rs = new ArrayList<Integer>();

ArrayList<Integer> ws = new ArrayList<Integer>();

ArrayList<Integer> bs = new ArrayList<Integer>();

int temp0 = 0;

int temp1 = 0;

int temp2 = 0;

ArrayList<Integer> zons = new ArrayList<Integer>();

int i = 0;

int length = nums.length;

for(; i < length;i++){

if(nums[i] == 0){

rs.add(nums[i]) ;

temp0++;

}else if(nums[i] == 1){

ws.add(nums[i]) ;

temp1++;

}else if(nums[i] == 2){

bs.add(nums[i]) ;

temp2++;

}else

break;

}

System.out.println(rs);

for(i = 0;i<temp0;i++){

zons.add(rs.get(i));

}

for(int j = 0;j<temp1;j++){

zons.add(ws.get(j));

}

for(int j = 0;j<temp2;j++){

zons.add(bs.get(j));

}

for(i = 0;i < length;i++){

nums[i] = zons.get(i);

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: