题目1
题解1
from queue import PriorityQueue
class Solution:
"""
将每个节点的值放入优先队列,依次取出构建排序链表
"""
def sortList(self, head: ListNode) -> ListNode:
pointer = head
pq = PriorityQueue()
while pointer:
pq.put(pointer.val)
pointer = pointer.next
pointer = head
while not pq.empty():
pointer.val = pq.get()
pointer = pointer.next
return head!
题目2
题解2
class Solution:
def insertionSortList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
p = head
List = []
while p:
List.append(p)
p = p.next
for i in range(1,len(List)):
j = i
while j > 0:
if List[j].val < List[j-1].val:
List[j], List[j-1] = List[j-1], List[j]
j -= 1
else:
break
FakerNode = ListNode('inf')
pointer = FakerNode
for node in List:
pointer.next = node
node.next = None
pointer = node
return FakerNode.next
题目3
题解3
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.od = OrderedDict()
def get(self, key: int) -> int:
if key not in self.od:
return -1
self.od.move_to_end(key)
return self.od[key]
def put(self, key: int, value: int) -> None:
if key in self.od:
del self.od[key]
elif len(self.od) >= self.capacity:
self.od.popitem(False)
self.od[key] = value
附上题目链接:
题目1链接
题目2链接
题目3链接