Leetcode_75_Sort Colors

本文介绍了一种针对红、白、蓝三色(用0、1、2表示)的数组排序算法,通过两次遍历实现了相同颜色相邻且按红、白、蓝顺序排列的目标。首次遍历统计每种颜色的数量,第二次遍历则根据数量填充数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.youkuaiyun.com/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--;
			}
		}
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值