Description
统计数组中不同整数的个数
Input Format
第一行读入一个整数 N
第二行读入 N 个整数, 构成数组A
Output Format
输出一个整数,表示数组A中不同的数的个数
解释: 比如 1 2 2 3 3 4 就有4种不同的数分别是1 2 3 4
Sample Input
10
1 3 3 4 2 2 4 1 1 5
Sample Output
5
Tips
1.时间复杂度必须是O(NlogN):利用快速排序预处理
2.题目中的N可能比较大,数组尽量开到1M的数量级
C++实现如下:
#include <iostream>
#define MaxSize 1000002
using namespace std;
template<class KEY, class OTHER>
struct SET {
KEY key;
OTHER other;
};
template<class KEY, class OTHER>
int divide(SET<KEY, OTHER> a[], int low, int high) {
SET<KEY, OTHER> k = a[low];
do {
while (low < high && a[high].key >= k.key) --high;
if (low < high) {
a[low] = a[high];
++low;
}
while (low < high && a[low].key <= k.key) ++low;
if (low < high) {
a[high] = a[low];
--high;
}
} while (low != high);
a[low] = k;
return low;
}
template<class KEY, class OTHER>
void quickSort(SET<KEY, OTHER> a[], int size) {
quickSort(a, 0, size - 1);
}
template<class KEY, class OTHER>
void quickSort(SET<KEY, OTHER> a[], int low, int high) {
int mid;
if (low >= high) return;
mid = divide(a, low, high);
quickSort(a, low, mid - 1);//排序左一半
quickSort(a, mid + 1, high);//排序右一半
}
SET<int, int> a[MaxSize];
int main() {
int n;
int counting = 1;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i].key;
}
quickSort(a, n);
for (int i = 0; i < n - 1; ++i) {
if (a[i].key != a[i + 1].key) {
counting++;
}
}
cout << counting;
return 0;
}