【算法概论】分治算法:数组去重

先进行归并排序,再一项项进行去重。

时间复杂度:O(n*logn)

#include <iostream>

using namespace std;

void mergeSort(int data[], int head, int tail);
void merge(int data[], int head, int mid, int tail);

int main()
{
	int n;
	cin >> n;
	
	int *data = new int[n];

	for (int i = 0; i < n; ++i)
	{
		cin >> data[i];
	}

	mergeSort(data, 0, n - 1);

	cout << data[0] << ' ';
	for (int i = 1; i < n; ++i)
	{
		if (data[i] != data[i - 1])
		{
			cout << data[i] << ' ';
		}
	}
	cout << endl;

	delete data;

	return 0;
}

void mergeSort(int data[], int head, int tail)
{
	if (head < tail)
	{
		int mid = (head + tail) / 2;
		mergeSort(data, head, mid);
		mergeSort(data, mid + 1, tail);

		merge(data, head, mid, tail);
	}

	return;
}

void merge(int data[], int head, int mid, int tail)
{
	int len1 = mid - head + 1;
	int len2 = tail - mid;

	int *L = new int[len1];
	int *R = new int[len2];

	for (int i = 0, k = head; i < len1; ++i, ++k)
	{
		L[i] = data[k];
	}
	for (int j = 0, k = mid+1 ; j < len2; ++j, ++k)
	{
		R[j] = data[k];
	}

	int i = 0, j = 0, k = head;
	while (i < len1 && j < len2)
	{
		if (L[i] > R[j])
		{
			data[k] = R[j];
			++j;
		}
		else if (L[i] < R[j])
		{
			data[k] = L[i];
			++i;
		}
		else
		{
			data[k] = L[i];
			++k;
			data[k] = R[j];
			++i;
			++j;
		}
		++k;
	}

	if (i == len1)
	{
		while (j < len2)
		{
			data[k++] = R[j++];
		}
	}
	if (j == len2)
	{
		while (i < len1)
		{
			data[k++] = L[i++];
		}
	}

	delete L;
	delete R;

	return;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值