日期:2025年11月1日
ZeroJudge 題目連結:g217. A.成雙成對(pairs)
解題想法
只要數量最多的數字不超過一半就可以符合要求。
Python 程式碼
collections.Counter 有一個很好用的功能 most_common,語法為
[Counter物件].most_common(數量)
回傳值格式為 list,串列中的資料格式為 tuple,內容為 (key, 數量)。使用時間約為 16 ms,記憶體約為 3.4 MB,通過測試。
from collections import Counter
t = int(input())
for _ in range(t):
n = int(input())
cnt = Counter(map(int, input().split()))
imax = cnt.most_common(1)[0][1]
print("Yes" if imax <= n//2 else "No")
C++ 程式碼
使用時間約為 2 ms,記憶體約為 280 kB,通過測試。
#include <cstdio>
#include <map>
using namespace std;
int main() {
int t; scanf("%d", &t);
while(t--) {
int n; scanf("%d", &n);
map<int, int> cnt;
for(int i=0; i<n; i++) {
int a; scanf("%d", &a);
cnt[a]++;
}
int imax = 0;
for(auto it : cnt) {
if (it.second > imax) {
imax = it.second;
}
}
if (imax > n/2) printf("No\n");
else printf("Yes\n");
}
return 0;
}
沒有留言:
張貼留言