Notice
Recent Posts
Recent Comments
Today
Total
01-10 18:14
Link
๊ด€๋ฆฌ ๋ฉ”๋‰ด

Partially Committed

[Algorithm] Tournament Winner ๋ณธ๋ฌธ

๐Ÿ”ฅ Algorithm || ๋ฌธ์ œํ’€์ด/PS

[Algorithm] Tournament Winner

WonderJay 2022. 10. 25. 10:43
728x90
๋ฐ˜์‘ํ˜•
SMALL

  ์˜ค๋Š˜ ํ’€์–ด๋ณผ ๋ฌธ์ œ ์ƒํ™ฉ์€ Tournament Winner ์ด๋‹ค. Problem solving ์‹ค๋ ฅ์„ ๊ฒจ๋ฃจ๋Š” Tournament Winner ๋Š” ์•„๋ž˜์˜ ๊ทœ์น™์„ ๋”ฐ๋ฅธ๋‹ค.

  • ๊ฐ๊ฐ์˜ team ์€ ์„œ๋กœ ๋‹ค๋ฅธ ์–ธ์–ด(C#, Python ...)๋ฅผ ์‚ฌ์šฉํ•œ๋‹ค.
  • ๊ฒฝ๊ธฐ ๋ฐฉ์‹์€ round-robin ๋ฆฌ๊ทธ์ œ์ด๋ฉฐ ๊ฐ ๊ฒฝ๊ธฐ ๋‹น home team, away team ์ด ์ง€์ •๋œ๋‹ค.
  • ๋Œ€์ง„ํ‘œ๋Š” competitions 2์ฐจ์› ๋ฐฐ์—ด์— ์ œ์‹œ๋˜๋ฉฐ ๊ฒฝ๊ธฐ ๊ฒฐ๊ณผ๋Š” results ๋ฐฐ์—ด๋กœ ์ฃผ์–ด์ง„๋‹ค.
    competitions = [
        ["HTML", "C#"],
        ["C#", "Python"],
        ["Python", "HTML"],
    ]
    results = [0, 0, 1]
    ์œ„์™€ ๊ฐ™์ด ์ฃผ์–ด์กŒ์„ ๋•Œ, ๊ฐ๊ฐ์˜ ๋Œ€์ง„ํ‘œ์˜ ์•ž์˜ ํŒ€์€ home, ๋’ค์— ํŒ€์€ away ์ด๋‹ค. ๊ทธ๋ฆฌ๊ณ  results ๊ฐ€ 0 ์ด๋ฉด away ๊ฐ€ ์ด๊ธด ๊ฒƒ์ด๋ฉฐ 1 ์ด๋ฉด home ํŒ€์ด ์Šน๋ฆฌํ•œ ๊ฒƒ์ด๋‹ค.
  • ๊ฒฝ๊ธฐ์— ์Šน๋ฆฌํ•œ ํŒ€์€ 3 point ๋ฅผ ์–ป๊ฒŒ ๋˜๋ฉฐ, ์ตœ์ข…์ ์œผ๋กœ ๊ฐ€์žฅ ๋งŽ์€ ์ ์ˆ˜๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” team ์ด ์šฐ์ŠนํŒ€์ด๊ณ , ์šฐ์ŠนํŒ€์ด ์—ฌ๋Ÿฌ๊ฐœ ๋‚˜์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ์ œ์™ธํ•œ๋‹ค.

  ๊ฐ๊ฐ์˜ ํŒ€์„ hash table ์— <teamname, score> ์˜ ํ˜•ํƒœ๋กœ ์ €์žฅํ•˜๋ฉด ๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค. competitions ๋ฐฐ์—ด์—์„œ teamname ์„ ๋ฝ‘์•„๋‚ด์„œ hash_table ์— {teamname, 0} ์˜ ํ˜•ํƒœ๋กœ insert ํ•ด์ค€๋‹ค. ๊ทธ๋ฆฌ๊ณ  ๊ฒฝ๊ธฐ ๊ฐœ์ˆ˜๋งŒํผ loop ๋ฅผ ๋Œ๋ฉฐ results ์˜ ์›์†Œ์— ๋”ฐ๋ผ์„œ home team, away team ์— 3์ ์„ ๋ถ€์—ฌํ•œ๋‹ค. ์ดํ›„์— hash_table ์„ ์ˆœํšŒํ•˜๋ฉฐ score ๊ฐ€ ๊ฐ€์žฅ ๋†’์€ teamname ์„ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค. 

  ๊ฒฝ๊ธฐ ๊ฐœ์ˆ˜๋ฅผ N, ํŒ€ ๊ฐœ์ˆ˜๋ฅผ K ๋ผ๊ณ  ํ–ˆ์„ ๋•Œ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(N) ์ด๊ณ  ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” O(K) ์ด๋‹ค.

#include <vector>
using namespace std;

// Time  : O(N) (N is # of competitions)
// Space : O(k) (k is # of teams) ~ hash map

string tournamentWinner(vector<vector<string>> competitions,
    vector<int> results) {
    // Write your code here.
    unordered_map<string, int> m;
    for (vector<string> ele : competitions) {
        m.insert({ ele[0], 0 });
        m.insert({ ele[1], 0 });
    }
    for (int i = 0; i < competitions.size(); i++) {
        if (results[i] == 1) {
            // home team win
            m[competitions[i][0]] += 3;
        }
        else {
            // away team win
            m[competitions[i][1]] += 3;
        }
    }
    string winner = ""; int max_pt = -1;
    for (auto ele : m) {
        if (ele.second > max_pt) {
            max_pt = ele.second;
            winner = ele.first;
        }
    }
    return winner;
}

https://github.com/versatile0010/AlgoExpert

 

GitHub - versatile0010/AlgoExpert: Solutions to AlgoExpert Problems.

Solutions to AlgoExpert Problems. Contribute to versatile0010/AlgoExpert development by creating an account on GitHub.

github.com

 

728x90
๋ฐ˜์‘ํ˜•
LIST
Comments