解題思路
排序後,相同值必定相鄰。
第一個元素算一種,其後僅在值與前一個不同時加一;每一種值恰在它的第一個位置被計入。
時間 O(n log n),讀取與排序記憶體 O(n)。
Step-by-step animation
教學例子:將 4、8、4、9、8、2 排序。
步驟 1 / 3
排序
將 4、8、4、9、8、2 排序。
2
4
4
8
8
9
- 種類
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<int> a(n);
for (auto &x : a)
cin >> x;
sort(a.begin(), a.end());
int s = 0;
for (int i = 0; i < n; i++)
if (i == 0 || a[i] != a[i - 1])
s++;
cout << s << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。