프로그래머스 - [1차] 캐시

well-life-gm·2021년 12월 19일
0

프로그래머스

목록 보기
93/125

프로그래머스 - [1차] 캐시

LRU를 구현하는 문제로 find, erase를 사용하면 금방 구현할 수 있다.

코드는 아래와 같다.

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int solution(int cacheSize, vector<string> cities) {
    int answer = 0;
    if(cacheSize == 0)
        return cities.size() * 5;
    
    vector<string> c;    
    for(auto it : cities) {
        transform(it.begin(), it.end(), it.begin(), ::tolower);
        auto exist = find(c.begin(), c.end(), it);
        if(exist != c.end()) {
            answer += 1;
            if(c.size() == cacheSize) 
                c.erase(exist);
        } else {
            answer += 5;
            if(c.size() == cacheSize)
                c.erase(c.begin());
        }
        c.push_back(it);
    }
    
    return answer;
}

결과

profile
내가 보려고 만든 블로그

0개의 댓글