蓝桥11

一LRU缓存机制

在这里插入图片描述

  • 创建两个量,记录最大容量,记录缓存信息
  • 获取值:如果存在,先将当前值pop出,然后再插入尾部,如果没有直接返回-1
  • 存值:如果已经存在,则直接取出,然后插入到尾部,如果不存在直接插入尾部
  • 存值时需要判定当前缓存是否超出最大限制,如果超出限制,则需要移除最前面的
class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.caches = dict()

    def get(self, key: int) -> int:
        # 获取一个元素,那么这个元素就要从字典中取出,然后将其移动到最后去
        if key in self.caches:
            val = self.caches[key]
            self.caches.pop(key)
            self.caches[key] = val
        return self.caches.get(key,-1)

    def put(self, key: int, value: int) -> None:
        # 如果值已经存在则移除
        if key in self.caches:
            self.caches.pop(key)
        self.caches[key] = value
        if len(self.caches) > self.capacity:
            first = [*self.caches.keys()][0]
            self.caches.pop(first)



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


二排序链表

在这里插入图片描述

  • 先记录链表的长度,
  • 创建一个数组,
  • 将链表中的数全部储存到数组中,
  • 然后通过数组Sort排序,
  • 最后用链表输出
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode SortList(ListNode head) {
        int len=0;
        ListNode p=head;
        while(p!=null)
        {
            len++;
            p=p.next;
        }
        int[] array=new int[len];
        p=head;
        for(int i=0;i<len;i++)
        {
            array[i]=p.val;
            p=p.next;
        }
        Array.Sort(array);
        p=head;
        for(int i=0;i<len;i++)
        {
            p.val=array[i];
            p=p.next;
        }
        return head;
    }
}


三最小栈

在这里插入图片描述

  • 定义两个空列表来充当栈结构,一个存放真正栈中的数据,一个存放栈中最小值的数据,在第一次push的时候,不管这个值是多少,都要放到存放最小值这个列表里面,在之后push值得时候,比较,当前插入得值是不是比,minstack列表中最后一个值小,小得话就插入,当删除栈中得值时,也需要和minstack中最后一个值比较,因为这样会节省内存,将不必要得值删除
class MinStack:

    def __init__(self):
        """
        initialize your data structure here.
        """
        self.item = []
        self.minstack = []

    def push(self, x: int) -> None:
        self.item.append(x)
        if not self.minstack or self.minstack[-1] >= x:
            self.minstack.append(x)

    def pop(self) -> None:
        if self.item.pop() == self.minstack[-1]:
            self.minstack.pop()
    
    def top(self) -> int:
        return self.item[-1]

    def getMin(self) -> int:
        return self.minstack[-1]
        



# 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()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值