b469簡單

只出現兩次

運用頻率表中的恰兩次種類,正確求解本題並處理邊界情況。

解題思路

先建立每個數值的出現次數。

遍歷頻率表,只將次數等於2的鍵算一次;這恰好對應題目要求的不同值,而不是位置數。

時間 O(N log N)(C++ map),Python 期望 O(N),空間 O(N)。

Step-by-step animation

教學例子:讀5、5、7、7、7,頻率表先有5:2。

回報動畫錯誤
步驟 1 / 3

步驟 1

讀5、5、7、7、7,頻率表先有5:2。

5:2
狀態
候選1種

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    map<int, int> cnt;
    while (n--) {
        int x;
        cin >> x;
        cnt[x]++;
    }
    int ans = 0;
    for (auto [x, c] : cnt)
        ans += c == 2;
    cout << ans << '\n';
}

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

更多