荷兰国旗问题 两种解法

问题介绍

给定一个包含红色、白色和蓝色,一共 n 个元素的数组,原地对它们进行排序,使得相同 颜色的元素相邻,并按照红色、白色、蓝色顺序排列。

解决方法

1.简单模拟实现。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <string>
using namespace std;
#pragma warning(disable:4996)   
//这是我常用的头文件,实际可能用不了这么多。但都写上。

//该方法的意思是让这三个变量表示颜色的最后一个的下标。
int main() {
	int n = 0;
	cin >> n;
	int* a;
	a = new int[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	int red = -1;
	int white = -1;
	int blue = -1;
	for (int i = 0; i < n; i++) {
		if (a[i] == 2) blue++;
		if (a[i] == 1) { blue++; white++; }
		if (a[i] == 0) { blue++; white++; red++; }
	}	
	for (int i = 0; i <=red; i++) {
		cout << 0<<" ";
	}
	for (int i = red+1; i <= white; i++) {
		cout << 1 << " ";
	}
	for (int i = white+1; i <=blue; i++) {
		cout << 2 << " ";
	}
	delete[]a;
}
2.利用快速排序的思想

快速排序利用的是分区域递归,这里设置前部,中部,后部三部分。分别对应0,1和2。主要思想是对“中部”进行操作。
设置三个“指针”。low指向第一位。high指向最后一位。还有一个遍历指针i,从头开始遍历。若遇到1,则i后移一位,若遇到0,则将i的值与low的值互换,i后移一位,low后移一位,若遇到2,则将i的值与high的值互换,则将i的值与high互换,high前移一位,i位置不变,因为新换过来的值可能是0,那就需要再换一次。
那为啥遇到0时不这么操作呢?因为0是要放到前面的,放在前面的一定是已经“排序好的”,因为是从前面开始遍历。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#include <algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <string>
using namespace std;
#pragma warning(disable:4996)

int main() 
{
	int n = 0;
	cin >> n;
	int* a;
	a = new int[n];
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}
	int low = 0;
	int high = n - 1;
	for (int i = 0; i < n&&i<=high;) {
		if (a[i] == 1) i++;
		else if(a[i]==0)
		{
			int temp = a[i];
			a[i] = a[low];
			a[low] = temp;
			i++;
			low++;
		}
		else if(a[i] == 2) {
			int temp = a[i];
			a[i] = a[high];
			a[high] = temp;
			high--;
		}
	}
	for (int i = 0; i < n; i++) {
		cout << a[i] << " ";
	}
	delete[]a;
	return 0;
}

好了,这是荷兰国旗问题的两种解法,谢谢阅读。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

指针的值是地址

觉得还不错,我会继续努力的。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值