leetcode:Sort Colors 【Java】
2016-03-04 10:04
465 查看
一、问题描述
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.
二、问题分析
利用两个计数器,红球计数器从前往后走,蓝球计数器从后往前走。
三、算法代码
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.
二、问题分析
利用两个计数器,红球计数器从前往后走,蓝球计数器从后往前走。
三、算法代码
public class Solution { public void sortColors(int[] nums) { int red = 0; int blue = nums.length - 1; int tmp = -1; for(int i = 0; i < blue + 1; ){ if(nums[i] == 0){ tmp = nums[red]; nums[red] = nums[i]; nums[i] = tmp; red++; i++; }else if(nums[i] == 2){ tmp = nums[i]; nums[i] = nums[blue]; //当找到蓝球时,计数器i值要保持不变 nums[blue] = tmp; blue--; }else{ i++; } } } }
相关文章推荐
- Java ArrayList的实现原理详解
- Spring在web请求中定义编码
- Spring MVC之@RequestBody, @ResponseBody 详解
- java hashset 使用
- 简述java内存模型
- 堆排序的java实现
- IT十八掌作业_java基础第二天_进制转换原理和补码存储方式
- Java多态例题
- 【leetcode】【91】Decode Ways
- Java关于排序的介绍3-高级排序
- Javassist简单应用小结
- JAVA CAS原理深度分析
- eclipse EasyExplore插件安装
- Spring Bean 生命周期2
- Eclipse配置信息
- JavaBean
- java中dynamic web project与web project 的区别
- 深入分析Java ClassLoader原理
- 简单模拟spring装载注入bean原理
- 【Javaweb】Eclipse for JavaEE新建的Web工程自动生成web.xml