LeetCode Tencent Featured Exercise 50-Day 12

Question 146: LRU Caching Mechanism
Use the data structure you know to design and implement an LRU (least recently used) caching mechanism.
Implement the LRUCache class:
LRUCache(int capacity) Initialize the LRU cache with a positive integer as capacity capacity
int get(int key) If the keyword key exists in the cache, return the value of the keyword, otherwise return -1.
void put(int key, int value) If the keyword already exists, change its data value; if the keyword does not exist, insert the set of "keyword-value". When the cache capacity reaches the upper limit, it should delete the oldest unused data value before writing new data to make room for the new data value.
answer:

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)

Operation result:
Insert picture description here
Question 148: Sorting Linked List
Give you the head node head of the linked list, please sort it in ascending order and return to the sorted linked list.
answer:

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

Running result:
Insert picture description here
Topic 155: Minimal stack
Design a stack that supports push, pop, and top operations, and can retrieve the smallest element in a constant time.
push(x)-Push element x onto the stack.
pop() —— Delete the element at the top of the stack.
top()-Get the top element of the stack.
getMin()-Retrieve the smallest element in the stack.
answer:

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

operation result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_44315884/article/details/113061350