- LRU 缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制 。
实现 LRUCache 类:
LRUCache(int capacity) 以正整数作为容量 capacity 初始化 LRU 缓存
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字-值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。
进阶:你是否可以在 O(1) 时间复杂度内完成这两种操作?
思路:
哈希表的存储是无序的,用OrderedDict() ,可以做到有序存储,存储的顺序按照进入字典的顺序
通过pop(key)可以得到key所对应的value
popitem()可以的到最后一个进表的value,而popitem(last=False)可以得到第一个进表的value
import collections
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.catch = collections.OrderedDict()
def get(self, key: int) -> int:
if key not in self.catch:
return -1
value = self.catch.pop(key)
self.catch[key] = value
return value
def put(self, key: int, value: int) -> None:
if key in self.catch:
self.catch.pop(key)
elif self.catch and self.capacity == 0:
self.catch.popitem(last=False)
else:
self.capacity -= 1
self.catch[key] = value
好棒,但是我写不出来。。。
148. 排序链表
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
各个排序算法的复杂度:时间复杂度在O(nlogN)的排序算法是快速排序,堆排序,归并排序。
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
mid = self.get_mid(head)
l = head
r = mid.next
mid.next = None
return self.merge(self.sortList(l), self.sortList(r))
def merge(self, p, q):
tmp = ListNode(0)
h = tmp
while p and q:
if p.val < q.val:
h.next = p
p = p.next
else:
h.next = q
q = q.next
h = h.next
if p:
h.next = p
if q:
h.next = q
return tmp.next
def get_mid(self, node):
if node is None:
return node
fast = slow = node
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
return slow
- 最小栈
设计一个支持 push ,pop ,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) —— 将元素 x 推入栈中。
pop() —— 删除栈顶的元素。
top() —— 获取栈顶元素。
getMin() —— 检索栈中的最小元素。
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
#额外加上一个列表记录最小值,min_stack[i]表示位置0到i之间的最小值
self.stack = []
self.min_stack = []
self.len=0
def push(self, x: int) -> None:
self.stack.append(x)
self.min_stack.append(x)
if not self.len:
self.min_stack[0] = x
else:
self.min_stack[self.len] = min(x,self.min_stack[self.len-1])
self.len+=1
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
self.len-=1
def top(self) -> int:
if not self.len:
return None
return self.stack[self.len-1]
def getMin(self) -> int:
if not self.len:
return None
return self.min_stack[self.len-1]
这三道题好难。。。