[프로그래머스 Lv2] 캐시

김태민·2026년 6월 29일

코딩테스트

목록 보기
5/6

최종 코드

from collections import deque

def solution(cacheSize, cities):
    que = deque()
    time = 0
    for city in cities:
        if cacheSize == 0:
            return len(cities) * 5
        
        city = city.lower()
        # cache hit 일 때
        if city in que:
            time += 1
            que.remove(city)
            que.append(city)
        # cache miss이고 캐시 공간이 있을 때
        elif len(que) < cacheSize and city not in que:
            que.append(city)
            time += 5
        # cache miss이고 캐시 공간이 없을 때
        else:
            que.popleft()
            time += 5
            que.append(city)
    
    return time

주의해야 할 것이 2개 있었는데

  • 캐시 사이즈는 0이 가능하다는 것 -> 이거때매 pop 에러가 생겨서 한참 못찾았다
  • cache hit일 때는 popleft가 아닌 remove를 해야한다는 것 -> 처음엔 큐 라고 판단해서 popleft를 썼다가 엉뚱한걸 지워버렸다
profile
빠르게 성장하는 개발자

0개의 댓글