LeetCode50题第12天

LeetCode第146题: 缓存机制

  1. 使用队列存放(键被加入或改动的时间, 键值)
  2. 使用字典存放{键: (键被加入或改动的时间, 值)}
  3. 如果需要删除某个键, 使用队列依次出队, 如果出队的的时间与键值对对应字典的时间相同, 删除即可
from queue import Queue    
import time
class LRUCache:

    def __init__(self, capacity: int):
        self.size = capacity
        self.box = {}
        self.q = Queue()
    def get(self, key: int) -> int:
        try:
            now = time.time()
            value = self.box[key][1]
            self.box[key] = (now, value)
            self.q.put((now, key))
            return value
        except KeyError:
            return -1

    def put(self, key: int, value: int) -> None:
        now = time.time()
        self.q.put((now, key))
        self.box[key] = (now, value)
        if len(self.box) > self.size:
            while True:
                mid = self.q.get()
                if self.box[mid[1]][0] == mid[0]:
                    del self.box[mid[1]]
                    break


# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

LeetCode148题: 排序链表

  1. 先遍历链表将其值存到列表中
  2. 对列表排序
  3. 写回即可
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: ListNode) -> ListNode:
        if head == None:
            return None
        list = []
        p = head
        while p != None:
            list.append(p.val)
            p = p.next
        list.sort()
        i = 0
        p = head
        length = len(list)
        while i < length:
            p.val = list[i]
            p = p.next
            i += 1
        return head

LeetCode第155题: 最小栈

  1. 在每次遍历压站和弹栈操作后更新最小值即可
class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.stack = []
        self.min = float('-inf')
    def push(self, x: int) -> None:
        self.stack.append(x)
        self.min = min(self.stack)
    def pop(self) -> None:
        resutl = self.stack.pop()
        if len(self.stack) == 0:
            return resutl
        self.min = min(self.stack)
        return resutl
    def top(self) -> int:
        return self.stack[len(self.stack) - 1]

    def getMin(self) -> int:
        if len(self.stack) <= 0:
            return None
        return self.min


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值