解題思路
先建立每個數值的出現次數。
遍歷頻率表,只將次數等於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種
#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';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。