알고리즘/LeetCode
LeetCode 풀기 - 146. LRU Cache
앤테바
2022. 3. 26. 15:00
반응형
146. LRU Cache
https://leetcode.com/problems/lru-cache/
LRU Cache - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제)
솔루션1) dict()
dict() 자료 구조를 이용해서 쉽게 풀 수 있습니다.
참고적으로, python 3.7 이상 부터의 dict는 데이터의 삽입 순서를 보장합니다.
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = {}
def get(self, key):
value = self.cache.get(key, -1)
if value == -1:
return value
del self.cache[key]
self.cache[key] = value
return value
def put(self, key, value):
# 이미 키가 있는 경우
if key in self.cache:
del self.cache[key]
self.cache[key] = value
return
if len(self.cache) >= self.capacity:
del self.cache[next(iter(self.cache))]
self.cache[key] = value
함께 보면 좋은 글:
반응형