本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/43302343

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.

思路:

(1)题意为给定一个数组,里面含有红白蓝三种颜色(顺序是打乱的),将其调整为红-->白-->蓝的顺序。其中,0,1,2分别对应红,白,蓝。

(2)该题的实质就是一个排序操作。只不过相同的元素比较多,需要确定下来。本文使用的方法比较简单,首先,遍历数组,确定0,1,2的个数;然后,再对数组进行遍历,依次将0,1,2填入数组中。具体操作为,只要0的个数大于零,就将0填入数组,然后个数减1,直到0全部放入数组为止,继续将1和2按照其对应的个数放入数组中。最后,所得的数组中就是以连续的0-->1-->2的顺序分布。

(3)希望本文对你有所帮助。

算法代码实现如下:

	/**
	 *
	 * @author liqq
	 */
	public void sortColors(int[] A) {
		if (A == null || A.length <= 1)
			return;

		int _zeor = 0;
		int _one = 0;
		int _two = 0;

		for (int i = 0; i < A.length; i++) {
			if (A[i] == 0)
				_zeor++;
			if (A[i] == 1)
				_one++;
			if (A[i] == 2)
				_two++;
		}

		for (int i = 0; i < A.length; i++) {
			if (_zeor > 0) {
				A[i] = 0;
				_zeor--;
				continue;
			}
			if (_one > 0) {
				A[i] = 1;
				_one--;
				continue;
			}

			if (_two > 0) {
				A[i] = 2;
				_two--;
			}
		}
	}

最新文章

  1. JavaScript (If...Else和Switch和循环遍历) 语句以及常用消息框
  2. 容器化redis高可用方案
  3. JS创建缩略图
  4. iOS CGContextRef画图时的常用方法
  5. Html5 dataset--自定义属性
  6. POJ 1276 Cash Machine
  7. python_类
  8. [原创]java WEB学习笔记48:其他的Servlet 监听器:域对象中属性的变更的事件监听器 (3 个),感知 Session 绑定的事件监听器(2个)
  9. 启动项目报错Error: listen EADDRINUSE
  10. leetcode 155. Min Stack --------- java
  11. HttpWebRequest和HttpWebResponse用法小结
  12. Win32多线程编程(1) — 基础概念篇
  13. foj 2150 Fire Game(bfs暴力)
  14. Windows编译Nodejs时遇到 File &quot;configure&quot;, line 313 SyntaxError: invalid syntax Failed to create vc project files. 时的解决方法
  15. 国民身份证号码校验之“C#/Winform方法实现+案例分析”
  16. 两个input在同一行连着不留缝隙
  17. 成功破解邻居的Wifi密码
  18. RTC实时时间系统学习笔记(一)---------------UART串口
  19. scrapy_redis 相关: 将 jobdir 保存的爬虫进度转移到 Redis
  20. day14 python各种推导式详解

热门文章

  1. SQL Server 虚拟化(1)——虚拟化简介
  2. Bootstrap3 排版-改变大小写
  3. 最大熵模型The Maximum Entropy
  4. Linux文件格式化与相关处理及sed工具
  5. SpringMVC基础配置(通过注解配置,非xml配置)
  6. Eclipse中配置javap命令
  7. EJB开发第一个无状态会话bean、开发EJB客户端
  8. JSP自定义方法库
  9. Shell 整数比较、字符串比较
  10. UE4使用C++创建枚举变量适用于C++与蓝图