先进行归并排序,再一项项进行去重。
时间复杂度: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;
}