https://programmers.co.kr/learn/courses/30/lessons/17680
코딩테스트 연습 - [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
내 풀이:
from collections import deque
def solution(cacheSize, cities):
# 예외 처리
if cacheSize == 0:
return 5 * len(cities)
cache = deque([0] * cacheSize)
time = 0
for city in cities:
city = city.lower()
# cache hit
if city in cache:
time += 1
cache.remove(city)
cache.appendleft(city)
# cache miss
else:
time += 5
cache.pop()
cache.appendleft(city)
return time
- 아이디어: 데크로 캐시 구성해 cities 탐색하면서 캐시에 앞에서부터 최근에 검색한 순서로 배치
- 예외 처리 더 신경 쓸 것
참고 풀이:
def solution(cacheSize, cities):
import collections
cache = collections.deque(maxlen=cacheSize)
time = 0
for i in cities:
s = i.lower()
if s in cache:
cache.remove(s)
cache.append(s)
time += 1
else:
cache.append(s)
time += 5
return time
- 동일한 아이디어지만 데크의 maxlen 기능을 이용해 cache miss 상황에서 pop()할 필요가 없어 더 간결한 코드
- 여기서는 캐시의 뒤로 갈수록 최근에 검색한 도시이름
'CS > algorithm & data structure' 카테고리의 다른 글
[프로그래머스] [3차] 압축 (파이썬 풀이) (0) | 2022.07.05 |
---|---|
[프로그래머스] [3차] 방금그곡 (파이썬 풀이) (0) | 2022.06.30 |
[프로그래머스] [1차] 프렌즈4블록 (파이썬 풀이) (0) | 2022.06.30 |
[프로그래머스] 후보키 (파이썬 풀이) (0) | 2022.06.30 |
[프로그래머스] 순위 검색 (파이썬 풀이) (0) | 2022.06.29 |