b379簡單

CSES 1621|相異數字(Distinct Numbers)

運用排序去除重複,正確求解本題並處理邊界情況。

解題思路

排序後,相同值必定相鄰。

第一個元素算一種,其後僅在值與前一個不同時加一;每一種值恰在它的第一個位置被計入。

時間 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

Reference solution

回報程式錯誤

完整程式

#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';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多