- 0
- 0
- 约7.75千字
- 约 24页
- 2026-02-19 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年美团技术专家面试题及解析
一、编程能力测试(共5题,每题20分,总分100分)
1.题目:
实现一个LRU(最近最少使用)缓存,支持get和put操作。缓存容量为capacity,get(key)返回key对应的值,如果key不存在返回-1;put(key,value)将key和value存入缓存,如果缓存已满,则删除最久未使用的项。
答案:
python
classLRUCache:
def__init__(self,capacity:int):
self.capacity=capacity
self.cache={}
self.order=[]
defget(self,key:int)-int:
ifkeyinself.cache:
self.order.remove(key)
self.order.append(key)
returnself.cache[key]
return-1
defput(self,key:int,value:int)-None:
ifkeyinself.cache:
self.order.remove(key)
eliflen(self.cache)=self.capacity:
oldest_key=self.order.pop(0)
delself.cache[oldest_key]
self.cache[key]=value
self.order.append(key)
解析:
LRU缓存的核心是维护一个有序的键列表,每次get操作将键移到末尾,put操作时如果键已存在则更新位置,如果缓存已满则删除最前面的键。这里使用字典存储键值对(O(1)时间复杂度),列表维护顺序(O(1)时间复杂度)。
2.题目:
给定一个链表,判断链表是否存在环。如果存在,返回入环点;否则返回None。
答案:
python
classListNode:
def__init__(self,x):
self.val=x
self.next=None
defdetectCycle(head:ListNode)-ListNode:
ifnothead:
returnNone
slow,fast=head,head
has_cycle=False
whilefastandfast.next:
slow=slow.next
fast=fast.next.next
ifslow==fast:
has_cycle=True
break
ifnothas_cycle:
returnNone
slow=head
whileslow!=fast:
slow=slow.next
fast=fast.next
returnslow
解析:
使用快慢指针(Floyd算法),快指针每次走两步,慢指针走一步。如果链表有环,快慢指针最终会相遇;相遇后慢指针重新从头开始,与快指针以相同速度移动,入环点即为相遇点。
3.题目:
实现一个二叉树的深度优先遍历(前序、中序、后序),并输出遍历结果。
答案:
python
classTreeNode:
def__init__(self,x):
self.val=x
self.left=None
self.right=None
defpreorder(root:TreeNode):
ifnotroot:
return[]
stack,res=[root],[]
whilestack:
node=stack.pop()
res.append(node.val)
ifnode.right:
stack.append(node.right)
ifnode.left:
stack.append(node.left)
returnres
definorder(root:TreeNode):
stack,res,node=[],[],root
whilestackornode:
whilenode:
stack.append(node)
node=node.left
node=stack.pop()
res.append(node.val)
node=node.right
returnres
defpostorder(root:TreeNode):
ifnotroot:
return[]
stack,res=[(root,False)],[]
whilestack:
node,visi
原创力文档

文档评论(0)