编程实践笔记No.12
写在最前面,编程一直是我的短板,希望在leetcode练习中获得进步!
参考Datawhale组队学习中“LeetCodeTencent”
题目一146 LRU缓存机制
运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。
写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
代码
class LRUCache:
def __init__(self, capacity: int):
self._capacity = capacity
self._dict = dict()
self._keys = list()
def get(self, key: int) -> int:
if key in self._dict:
self._keys.remove(key)
self._keys.append(key)
return self._dict[key]
return -1
def put(self, key: int, value: int) -> None:
if key in self._dict:
self._dict.pop(key)
self._keys.remove(key)
elif len(self._keys) == self._capacity:
self._dict.pop(self._keys[0])
self._keys.remove(self._keys[0])
self._keys.append(key)
self._dict[key] = value
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
题目二141 环形链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
思路
快慢指针
如果是链表中有环,快慢指针将会相遇。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head is None:
return head
return self.mergeSort(head)
def mergeSort(self, node: ListNode) -> ListNode:
if node.next is None:
return node
p1 = node
p2 = node
cute = None
while p1 is not None and p1.next is not None:
cute = p2
p2 = p2.next
p1 = p1.next.next
cute.next = None
l1 = self.mergeSort(node)
l2 = self.mergeSort(p2)
return self.mergeTwoLists(l1, l2)
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
pHead = ListNode(-1)
temp = pHead
while l1 is not None and l2 is not None:
if l1.val < l2.val:
temp.next = l1
l1 = l1.next
else:
temp.next = l2
l2 = l2.next
temp = temp.next
if l1 is not None:
temp.next = l1
if l2 is not None:
temp.next = l2
return pHead.next
题目三155 最小栈
设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
代码
class MinStack:
def __init__(self):
self.stack = []
self.min_stack = [math.inf]
def push(self, x: int) -> None:
self.stack.append(x)
self.min_stack.append(min(x, self.min_stack[-1]))
def pop(self) -> None:
self.stack.pop()
self.min_stack.pop()
def top(self) -> int:
return self.stack[-1]
def getMin(self) -> int:
return self.min_stack[-1]
本文介绍了三个编程题目:1)LRU缓存机制,通过双链表和哈希表实现;2)环形链表的判断与排序,利用快慢指针检测环并用归并排序;3)最小栈,维护一个额外栈保存最小值。通过这些题目提升数据结构与算法能力。
1122

被折叠的 条评论
为什么被折叠?



