프로그래머스/Level_2

[Level_2 / C++ / 카카오] [1차] 캐시

배발자 2022. 1. 24.
반응형

1. cacheSize 가 0이면 return 도시의 개수 X 5 

2. 문자열 대문자로 변환 (소문자, 대문자 구분하지 않는다) 

3. map 생성하여 제일 작은 cnt값을 갖는 key 문자열 저장 

4. (주의) hit를 해도 cnt 값 갱신

5. 제일 작은 cnt값을 갖는 key 문자열에 해당하는 map을 지우고 새로운 값 추가 

#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <climits>
#include <iostream>
using namespace std;
int solution(int cacheSize, vector<string> cities) {
    int answer = 0;     
    map <string, int> m; 
    int cnt =1;    
    if(cacheSize==0)return cities.size()*5;     
    for(int i=0; i<cities.size(); i++){ //문자열 대문자 변환 
        string s= cities[i]; 
        for(int j=0; j<s.size(); j++){
            if(s[j]>='a'&&s[j]<='z'){
                s[j]= toupper(s[j]); 
            }
        }                
        int check =0;
        string s1 = ""; 
        int min_n=INT_MAX;          
        for(auto x : m){      
            if(x.first==s){
                check=1; 
                m[s]=cnt;        
                answer+=1; 
            }
           if(min_n>x.second){
               min_n = x.second; 
               s1 = x.first; 
           }           
        }
        if(!check){        
            if(m.size()<cacheSize) m[s]=cnt; 
            else{    
                m.erase(s1);
                m[s]=cnt;                    
            }          
            answer+=5; 
        }             
        cnt++;
    }    
    return answer;
}
 

코딩테스트 연습 - [1차] 캐시

3 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "Jeju", "Pangyo", "Seoul", "NewYork", "LA"] 50 3 ["Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul", "Jeju", "Pangyo", "Seoul"] 21 2 ["Jeju", "Pangyo", "Seoul", "NewYork", "LA", "SanFrancisco", "Seoul", "Ro

programmers.co.kr

반응형

댓글