質問146:LRUキャッシングメカニズム
既知のデータ構造を使用して、LRU(最近使用されていない)キャッシングメカニズムを設計および実装します。
LRUCacheクラスを実装します
。LRUCache(intcapacity)容量容量として正の整数を使用してLRUキャッシュを初期化します。intget(int
key)キーワードkeyがキャッシュに存在する場合は、キーワードの値を返します。それ以外の場合は-1を返します。
void put(int key、int value)キーワードがすでに存在する場合は、そのデータ値を変更します。キーワードが存在しない場合は、「keyword-value」のセットを挿入します。キャッシュ容量が上限に達すると、新しいデータを書き込む前に最も古い未使用のデータ値を削除して、新しいデータ値のためのスペースを確保する必要があります。
回答:
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.cache = {
}
def get(self, key: int) -> int:
if key not in self.cache:
return -1
self.cache[key] = self.cache.pop(key)
return self.cache[key]
def put(self, key: int, value: int) -> None:
if key in self.cache:
self.cache.pop(key)
self.cache[key] = value
if len(self.cache) > self.capacity:
x = list(self.cache)[0]
self.cache.pop(x)
演算結果:
質問148:リンクリストのソートリンクリスト
のヘッドノードヘッドを表示します。昇順でソートして、ソートされたリンクリストに戻ってください。
回答:
class Solution:
def sortList(self, head: ListNode) -> ListNode:
nodes = []
while head:
nodes.append(head)
head = head.next
nodes = sorted(nodes, key = lambda x: x.val)
cur = head = ListNode()
for i in range(len(nodes)):
cur.next = nodes[i]
cur = cur.next
cur.next = None
return head.next
実行結果:
トピック155:最小スタック
プッシュ、ポップ、およびトップ操作をサポートし、一定時間で最小の要素を取得できるスタックを設計します。
push(x)-要素xをスタックにプッシュします。
pop()-スタックの最上位にある要素を削除します。
top()-スタックの最上位要素を取得します。
getMin()-スタック内の最小の要素を取得します。
回答:
class MinStack:
def __init__(self):
self._list = []
def push(self, x: int) -> None:
self._list.append(x)
self._min = min(self._list)
def pop(self) -> None:
self._list.pop()
self._min = not self._list or min(self._list)
def top(self) -> int:
return self._list[-1]
def getMin(self) -> int:
return self._min
演算結果: