LeetCode腾讯精选练习50——第十二天

题目146:LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int 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:排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
题解:

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 ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
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

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44315884/article/details/113061350