๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][ํ•ด์‹œ] ์˜์ƒ (feat. hash map ๋ฐ˜๋ณต๋ฌธ)

ibelieveinme 2023. 5. 16. 23:51
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/42578?language=cpp 

 

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

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

programmers.co.kr

 

*ํ’€์ด

์˜์ƒ์กฐํ•ฉ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ๋กœ, ์˜์ƒ์˜ ์ข…๋ฅ˜๋ฅผ key๋กœ ์˜์ƒ์˜ ์ข…๋ฅ˜๊ฐœ์ˆ˜๋ฅผ value๋กœ hash map์œผ๋กœ ํ‘œํ˜„ํ•ด์„œ

์˜์ƒ์ข…๋ฅ˜๊ฐœ์ˆ˜์˜ ์กฐํ•ฉ์„ ๊ณ„์‚ฐํ•˜๋ฉด๋œ๋‹ค(๊ณฑ์…ˆ  ์—ฐ์‚ฐ)

 

*์•Œ์•„๋‘˜ ๊ฒƒ

[hash map ๋ฐ˜๋ณต๋ฌธ ํƒ์ƒ‰๋ฐฉ๋ฒ•]

hash map์— ๋ฐ˜๋ณต๋ฌธ์„ ์ ์šฉํ•  ๋•Œ iterator๋ฅผ ์ด์šฉํ•˜๊ฑฐ๋‚˜ foreach ๋ฅผ ์ด์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

 

1) iterator์„ ์ด์šฉํ•œ hash map ๋ฐ˜๋ณต๋ฌธ

unordered_map<string, int>::iterator it;
for(it = map.begin(); it != map.end(); it++){
	cout << it->first << " " << it->second << "\n";
}

iterator ๋ฅผ ๋งŒ๋“ค๊ณ  ->๋กœ ์ ‘๊ทผํ•œ๋‹ค.

 

2) foreach๋ฅผ ์ด์šฉํ•œ hash_map ๋ฐ˜๋ณต๋ฌธ

for (auto& i : map) {
    cout << i.first << " " << i.second << endl;
}

auto& ๋ฌธ์œผ๋กœ ์ž๋™์œผ๋กœ ๋ฐ์ดํ„ฐํ˜•์„ ์ง€์ •ํ•˜๊ฑฐ๋‚˜ pair(string, int> i ๋กœ ํ˜•์„ ์ง€์ •ํ•ด์ฃผ๊ณ 

. ์œผ๋กœ ์ ‘๊ทผํ•ด์„œ ์‚ฌ์šฉํ•œ๋‹ค.

 

*์ฝ”๋“œ

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

int solution(vector<vector<string>> clothes) {
    int answer = 1;
    unordered_map<string, int> map;
    
    //1. ์˜ท ์ข…๋ฅ˜๋ฅผ key๋กœ ๋‘๊ณ  ์˜ท ์ข…๋ฅ˜๋ฅผ ์„ผ๋‹ค.
    for(auto& i: clothes){
        map[i[1]]++;
    }
    
    //2. ์˜ท ์ข…๋ฅ˜ ๊ฐœ์ˆ˜๋งŒํผ ๊ณฑํ•ด์„œ ์กฐํ•ฉ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.
    unordered_map<string, int>::iterator it;
    for(it = map.begin(); it != map.end(); it++){
        //์˜ท ์ข…๋ฅ˜ ๊ฐœ์ˆ˜์— ์ฐฉ์šฉ์•ˆํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ +1ํ•œ ๊ฒƒ.
        answer *= (it->second +1);
    }
    
    //3. ์ „๋ถ€ ์ฐฉ์šฉ ์•ˆํ•˜๋Š” ๊ฒฝ์šฐ 1๊ฐ€์ง€๋ฅผ ์ œ์™ธํ•œ๋‹ค.
    answer--;
    
    return answer;
}

iterator ๋กœ ๋ฐ˜๋ณต๋ฌธ์„ ๋Œ๋ ธ์—ˆ๋Š”๋ฐ ๊ฒ€์ƒ‰ํ•ด๋ณด๊ณ  ์•„๋ž˜์ฒ˜๋Ÿผ ๊ณ ์ณค๋‹ค.

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

int solution(vector<vector<string>> clothes) {
    int answer = 1;
    unordered_map<string, int> map;
    
    //1. ์˜ท ์ข…๋ฅ˜๋ฅผ key๋กœ ๋‘๊ณ  ์˜ท ์ข…๋ฅ˜๋ฅผ ์„ผ๋‹ค.
    for(auto& i: clothes){
        map[i[1]]++;
    }
    
    //2. ์˜ท ์ข…๋ฅ˜ ๊ฐœ์ˆ˜๋งŒํผ ๊ณฑํ•ด์„œ ์กฐํ•ฉ ๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.
    for(pair<string, int> i: map){
         //์˜ท ์ข…๋ฅ˜ ๊ฐœ์ˆ˜์— ์ฐฉ์šฉ์•ˆํ•˜๋Š” ๊ฒฝ์šฐ๋ฅผ ์ถ”๊ฐ€ํ•ด์„œ +1ํ•œ ๊ฒƒ.
        answer *= (i.second + 1);
    }
    
    //3. ์ „๋ถ€ ์ฐฉ์šฉ ์•ˆํ•˜๋Š” ๊ฒฝ์šฐ 1๊ฐ€์ง€๋ฅผ ์ œ์™ธํ•œ๋‹ค.
    answer--;
    
    return answer;
}

pair<string, int> i ๋ฅผ auto& i ๋กœ ๋ณ€๊ฒฝ๊ฐ€๋Šฅํ•จ !

728x90