【題解】APCS 2022年6月 P1. 數字遊戲

題目

輸入:3 個介於 1 到 9 之間的整數。
輸出:出現同一數字的最多次數、不重複的數字(大到小)。
範例:輸入:1 1 3。最多次數:2,不重複的數字(大到小):3 1。
題目連結:ZeroJudge

解法1:陣列

#include <iostream>
using namespace std;
int main(){
    int a[10] = {0};
    int x, Max=0;
    for(int i=0; i<3; i++){
        cin >> x;
        a[x]++;
        Max = max(Max, a[x]);
    }
    cout << Max << ' ';
    for(int i=9; i>=1; i--)
        if(a[i]) cout << i << ' ';
}

解法2:使用 set 資料結構

set:元素不重複、自動排序的資料結構。

#include <iostream>
#include <set>
using namespace std;
int main(){
    set<int, greater<int>> s;
    int x;
    for(int i=0; i<3; i++){
        cin >> x;
        s.insert(x);
    }
    cout << 4-s.size() << ' ';
    for(auto i:s) cout << i << ' ';
}
發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *