【leetcode】【75】Sort Colors

一、问题描述

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.计数,不过需要two pass
2.排序,可以自己写快排
3.双指针法 或者叫三指针
一个指针notred从左开始找,指向第一个不是0(红色)的位置;一个指针notblue从右开始往左找,指向第一个不是2(蓝色)的位置。
然后另一个新的指针i指向notred指向的位置,往后遍历,遍历到notblue的位置。
这途中需要判断:
当i指向的位置等于0的时候,说明是红色,把他交换到notred指向的位置,然后notred++,i++。
当i指向的位置等于2的时候,说明是蓝色,把他交换到notblue指向的位置,然后notred--。
当i指向的位置等于1的时候,说明是白色,不需要交换,i++即可。

三、Java AC代码

1.自己写快排

public void qSort(int[] nums, int left, int right) {
		int low = left, high = right;
		if (low >= high) {
			return;
		}
		int key = nums[low];
		while (low < high) {
			while (low < high && nums[high] >= key)
				high--;
			nums[low] = nums[high];
			while (low < high && nums[low] <= key)
				low++;
			nums[high] = nums[low];
		}
		nums[low] = key;
		qSort(nums, left, low - 1);
		qSort(nums, low + 1, right);
	}

	public void sortColors(int[] nums) {
		qSort(nums, 0, nums.length-1);
	}


2.双指针

public void sortColors(int[] nums) {
		int notRed = 0;
		int notBlue = nums.length-1;
		while(notRed<nums.length && nums[notRed]==0) notRed++;
		while(notBlue>=0 && nums[notBlue]==2) notBlue--;
		int p = notRed;
		while(p<=notBlue){
			if (nums[p]==2) {
				nums[p] = nums[notBlue];
				nums[notBlue] = 2;
				notBlue--;
			}else if (nums[p]==0) {
				nums[p] = nums[notRed];
				nums[notRed] = 0;
				notRed++;
				p++;
			}else p++;
		}
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值