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. 

一、题目要求:

对一个包含0,1,2三种数字的数组(其中0,1,2分别表示红色白色和蓝色)重新排序, 使得排好序的数组前一段都是0,中间一段都是  1,最后一段都是 2。

二、解题思路:
变量left,表示左边全0区域的最右位置,初始时left为-1;
变量index,利用这个变量从左到右对数组进行遍历,从left+1位置到index这个区域都是1,index就是这个全1区域的最右位置,  初始时为0;
变量right,从right到数组最后一个元素的区域都是2,right是这个区域最左的位置,初始right为数组最后一个元素的位置;当index开始遍历时,

(1).若nums[index]==1,则这个值直接加入中间区域,index++;
(2).若nums[index]==0,这个值应加入左区,nums[left+1]是中区最左位置,把nums[index]与nums[left+1]交换之后,左区就扩大  了,index++后继续 遍历;
(3).若nums[index]==2,这个值应该加入右区,nums[right-1]是右区最左边的数的左边,但也不属于中区,因为中区还未完全分开,  里面可能还有些0 和2,因此把nums[index]和nums[right-1]交换后,右区向左扩大了,但是交换后index位置的nums[index]未知,所以index不变;
当index==right时,表示中区与右区成功对接,三个区域都划分完成,过程结束。

遍历过程中,要么是index增加,要么right减少,如果index==right,则过程停止。


//题目要求:
//对一个包含0,1,2三种数字的数组(其中0,1,2分别表示红色白色和蓝色)重新排序,
//使得排好序的数组前一段都是0,中间一段都是1,最后一段都是2。
//解题思路:
//变量left,表示左边全0区域的最右位置,初始时left为-1;
//变量index,利用这个变量从左到右对数组进行遍历,从left+1位置到index这个区域都是1,index就是这个全1区域的最右位置,初始时为0;
//变量right,从right到数组最后一个元素的区域都是2,right是这个区域最左的位置,初始right为数组最后一个元素的位置;
//当index开始遍历时,若nums[index]==1,则这个值直接加入中间区域,index++;
//若nums[index]==0,这个值应加入左区,nums[left+1]是中区最左位置,把nums[index]与nums[left+1]交换之后,左区就扩大了,index++后继续遍历;
//若nums[index]==2,这个值应该加入右区,nums[right-1]是右区最左边的数的左边,但也不属于中区,因为中区还未完全分开,里面可能还有些0和2,
//因此把nums[index]和nums[right-1]交换后,右区向左扩大了,但是交换后index位置的nums[index]未知,所以index不变;
//当index==right时,表示中区与右区成功对接,三个区域都划分完成,过程结束。
//遍历过程中,要么是index增加,要么right减少,如果index==right,则过程停止。

 class Solution {
 public:
	 void sortColors(vector<int>& nums) {
		 int n = nums.size();
		 if (n == 0 || n < 2)
			 return;
		 int left = -1;
		 int index = 0;
		 int right = n;
		 while (index < right)
		 {
			 if (nums[index] == 0)
				 swap(nums[index++], nums[++left]);
			 else if (nums[index] == 2)
				 swap(nums[index], nums[--right]);
			 else
				 index++;
		 }
	 }
 };




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值