import java.util.Arrays;

/**
* 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. click to show follow up. Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's. Could you come up with an one-pass algorithm using only constant space?
*/
/*
* 两种解法
* 1.三个指针:红指针,蓝指针,遍历指针(循环指针i),红蓝指针比别从前后端记录红色区域和蓝色区域的边界位置,
* 遍历指针负责找到红蓝颜色的数据,白色的不用管,最后中间剩下的就是白色
* 2.记录红白蓝三色出现的次数,最后直接对数组进行相应的赋值
* 这里选用第一种
* 容易出错的地方:遍历指针和边界指针交换之后,还要在遍历指针的位置再判断一下是不是其他颜色,
* 所以比较适合写成两个if分别判断,而且后边的if要加i--*/
public class Q75SortColors {
public static void main(String[] args) {
int[] nums = new int[]{2,2,2};
sortColors(nums);
System.out.println(Arrays.toString(nums));
}
public static void sortColors(int[] nums) {
int red = 0;
int blue = nums.length - 1;
int temp;
//获取红色区域的初始边界
for (int i =0;i < nums.length;i++)
{
if (nums[i] != 0)
{
red = i;
break;
} }
//获取蓝色区域的初始边界
for (int i =nums.length-1;i >= 0 ;i--)
{
if (nums[i] != 2)
{
blue = i;
break;
} }
//遍历交换归位
for (int i =red;i <= blue ;i++)
{
if (nums[i] == 0)
{
temp = nums[red];
nums[red] = nums[i];
nums[i] = temp;
red++;
}
if (nums[i] == 2)
{
temp = nums[blue];
nums[blue] = nums[i];
nums[i] = temp;
blue--;
i--;
}
}
}
}

最新文章

  1. Android 学习笔记之一 “Unable to establish loopback connection”
  2. linux库列表
  3. JAVA基础知识之多线程——三种实现多线程的方法及区别
  4. django1.77+mod_wsgi+python2.79+apache2.24 在阿里云centos部署攻略
  5. mybatis-generator-core自动生成do、mapping、dao 代码
  6. 重载,重写和super
  7. InnoSetup中枚举出INI文件的所有sections和键值
  8. Memcahce(MC)系列(两)Linux下一个Memcache安装
  9. java 缓存ehcache的使用(使用方式一)
  10. python课程day_2--&gt;总结--&gt;字符串功能
  11. myeclipse的快捷键
  12. LDA主体模型
  13. ubuntu安装docker-ce
  14. LeetCode - 766. Toeplitz Matrix
  15. 北大poj- 1006
  16. COGS.1272.[AHOI2009]行星序列(线段树 区间加、乘、求和)
  17. 微信小程序开发小技巧——单击事件传参、动态修改样式、轮播样式修改等
  18. mongodb副本集升级步骤
  19. 构造方法,this关键字,static关键字,封装
  20. linux内核分析--操作系统是如何工作的?

热门文章

  1. 手把手教你使用Vue/React/Angular三大框架开发Pagination分页组件
  2. Django----Serializer序列化
  3. dubbo源码学习(二)dubbo容器启动流程简略分析
  4. ModelViewSet里的过滤、排序、分页、序列化设置
  5. 攻防世界 web进阶区 lottery
  6. 图论补档——KM算法+稳定婚姻问题
  7. 写给OIer们的一些话(修订版)
  8. AT2688 [ARC080C] Young Maids
  9. Hyper-v 虚拟机使用NAT方式连接网络
  10. Java NIO之Buffer(缓冲区)