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);
}
}
}
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);
}
}
}
相关文章推荐
- linux下网络环境配置
- CentOS6 下安装JDK7
- LeetCode "Closest Binary Search Tree Value II"
- C++ const
- 机房收费系统——组合查询
- POJ 1655 Balancing Act&&POJ 3107 Godfather(树的重心)
- Ubuntu下QNX SDP 6.6安装使用指南
- JBPM 数据表说明
- jquery学习笔记----jquery相关的文档
- Comparable接口和Comparator类的使用
- 后缀数组 - poj2774 Long Long Message
- Hibernate学习笔记
- Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()
- 自我总结:找工作面试时注意事项
- docker+tomcat+java配置(ubuntu)
- 36辆自动赛车和6条跑道的问题
- jquery学习笔记----ajax使用
- MySQL二进制日志
- jQuery实现自定义右键菜单的树状菜单效果
- PAT-01-复杂度2 Maximum Subsequence Sum