๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿ“ ์•Œ๊ณ ๋ฆฌ์ฆ˜/Programmers

[C++/PGS] Lv.1 : ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ (ํ•ด์‹œ๋งต Map)

728x90

 

https://school.programmers.co.kr/learn/courses/30/lessons/178871

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

 

์ฒ˜์Œ์— 2์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ–ˆ๋”๋‹ˆ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋œจ๊ธธ๋ž˜,

ํ•ด์‹œ๋งต์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒƒ์„ ๊นจ๋‹ฌ์•˜๋‹ค

Map์„ 2๊ฐœ ์“ฐ๋Š” ๋ฐฉ์‹ ๋“ฑ ํ’€์ด๊ฐ€ ๋‹ค์–‘ํ–ˆ๋Š”๋ฐ, ๋‚˜๋Š” unordered map ํ•˜๋‚˜๋กœ players์˜ ์ธ๋ฑ์Šค๋ฅผ ๋ฐ”๋กœ ๊ฒ€์ƒ‰ํ•ด์„œ ํ•ด๊ฒฐํ•จ

 

๋‚˜์˜ ํ’€์ด

#include <string>
#include <vector>
#include <unordered_map>
using namespace std;

vector<string> solution(vector<string> players, vector<string> callings) {
    vector<string> answer;
    unordered_map<string, int> m; // key=์„ ์ˆ˜์ด๋ฆ„, value=๋“ฑ์ˆ˜
    int len = players.size();
    for(int p=0; p<len; ++p){
        m[players[p]] = p;
    }
    
    for(int i=0; i<callings.size(); ++i){
        int cnt = m[callings[i]];
        string tmp = players[cnt-1]; // players ์ธ๋ฑ์Šค ๋ฐ”๋กœ ์ฐพ์•„์„œ ๋ณ€๊ฒฝ
        players[cnt-1] = players[cnt];
        players[cnt] = tmp;
        m[callings[i]] -= 1;
        m[tmp] += 1;
    }
    
    return players;
}
728x90