NC78+NC93

NC78 反转列表

描述

输入一个链表,反转链表后,输出新链表的表头。

示例1

输入:

{1,2,3}

返回值:

{3,2,1}

是一道简单题,主要考察链表。

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead:
            return None
        root = None
        while pHead:
            pHead.next,root,pHead = root,pHead,pHead.next
        return root


. 链表


在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
看到一个示意图感觉很清晰

主要收获:

python的同时赋值机制相当于把值分别读出来,再分别赋值进入需要赋值的变量,它们之间是没有先后关系的,可以理解成是同时赋值。

NC93 设计LRU缓存结构

描述

设计LRU缓存结构,该结构在构造时确定大小,假设大小为K,并有如下两个功能

  • set(key, value):将记录(key, value)插入该结构
  • get(key):返回key对应的value值

[要求]

  1. set和get方法的时间复杂度为O(1)
  2. 某个key的set或get操作一旦发生,认为这个key的记录成了最常使用的。
  3. 当缓存的大小超过K时,移除最不经常使用的记录,即set或get最久远的。

若opt=1,接下来两个整数x, y,表示set(x, y)
若opt=2,接下来一个整数x,表示get(x),若x未出现过或已被移除,则返回-1
对于每个操作2,输出一个答案

示例1

输入:

[[1,1,1],[1,2,2],[1,3,2],[2,1],[1,4,4],[2,2]],3

返回值:

[1,-1]

说明:

第一次操作后:最常使用的记录为("1", 1)
第二次操作后:最常使用的记录为("2", 2),("1", 1)变为最不常用的
第三次操作后:最常使用的记录为("3", 2),("1", 1)还是最不常用的
第四次操作后:最常用的记录为("1", 1),("2", 2)变为最不常用的
第五次操作后:大小超过了3,所以移除此时最不常使用的记录("2", 2),加入记录("4", 4),并且为最常使用的记录,然后("3", 2)变为最不常使用的记录

备注:

1≤K≤N≤1051 \leq K \leq N \leq 10^51≤K≤N≤105
−2×109≤x,y≤2×109-2 \times 10^9 \leq x,y \leq 2 \times 10^9−2×109≤x,y≤2×109

是一道中等题,考察内容为模拟和数据结构。

#
# lru design
# @param operators int整型二维数组 the ops
# @param k int整型 the k
# @return int整型一维数组
#
from collections import OrderedDict

class Solution:
    def __init__(self):
        self.cache = OrderedDict()
    
    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]
        
    def set(self, key, value, k):
            if key in self.cache:
                self.cache.move_to_end(key)
            self.cache[key] = value
            if len(self.cache) > k:
                self.cache.popitem(last=False)
    
        # write code here
    def LRU(self, operators, k ):
        result = []
        for opt in operators:
            if opt[0] == 1:
                self.set(opt[1], opt[2], k)
            elif opt[0] == 2:
                result.append(self.get(opt[1]))
        return result
        
        # write code here

主要收获:

学习python3的collections.OrderedDict类

这是一个有序字典,在字典的添加和删除过程中维护一个有序队列,插入的时候在队列尾端插入。但是初始化时依然是无需字典。

需要注意的方法:

def popitem(self, last=True):
    '''Remove and return a (key, value) pair from the dictionary.

    Pairs are returned in LIFO order if last is true or FIFO order if false.
    '''
def move_to_end(self, key, last=True):
    '''Move an existing element to the end (or beginning if last is false).

    Raise KeyError if the element does not exist.
    '''

这里的 move to end指的是队列尾端,也是队列入口端。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值