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

来源:互联网 发布:网络教育是什么学历 编辑:程序博客网 时间:2024/06/05 02:40

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


}
}

0 0
原创粉丝点击