ZeroJudge B130: 明明的隨機數

題目敘述

每筆資料第一行有一個正整數N,第二行有N個整數。要求輸出有幾個不重複的數字並將那些數字排序後輸出 (輸出格式請參照輸出範例)。


範例輸入

10

20 40 32 67 40 20 89 300 400 15

範例輸出

8

15 20 32 40 67 89 300 400


解題思路

可以使用Map來判斷該數有沒有出現過,如果有出現過的話就不要塞到陣列/Vector中,沒有出現過的話就塞到陣列裡並把Map值+1。最後輸出陣列大小還有sort之後的陣列幾可。

解題程式碼如下 (僅供參考):

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

int main() {
    cin.sync_with_stdio(0);
    cin.tie(0);
    int N;
    cin >> N;
    vector<int>num;
    map<int, int>MAP;
    for (int i = 0; i<N; i++)
    {
        int tmp;
        cin >> tmp;
        if (MAP[tmp] == 0) num.push_back(tmp);
        MAP[tmp]++;
    }
    sort(num.begin(), num.end());
    int size = int(num.size());
    cout << size << "\n";
    for (int i = 0; i<size; i++)
    {
        cout << num[i] << " ";
    }
    cout << "\n";
}

留言

這個網誌中的熱門文章

ZeroJudge M933: 邏輯電路

ZeroJudge A148: You Cannot Pass?!

ZeroJudge M932: 蜜蜂觀察