2026年美团技术部面试经验及答案参考.docxVIP

  • 0
  • 0
  • 约5.19千字
  • 约 15页
  • 2026-01-15 发布于福建
  • 举报

2026年美团技术部面试经验及答案参考.docx

第PAGE页共NUMPAGES页

2026年美团技术部面试经验及答案参考

一、编程能力测试(15分,共3题)

1.算法题(6分)

题目:

给定一个包含重复数字的数组,请找出数组中不重复的数字,并统计它们的数量。要求时间复杂度O(n),空间复杂度O(1)。

答案:

python

defcount_unique_numbers(nums):

对数组进行排序

nums.sort()

count=0

prev=None

fornuminnums:

ifnum!=prev:

count+=1

prev=num

returncount

示例输入

nums=[1,2,3,2,4,3,5,5,6]

print(count_unique_numbers(nums))#输出:5

解析:

-首先对数组进行排序,重复的数字会相邻。

-遍历排序后的数组,通过比较当前数字与前一个数字是否相同来统计不重复的数字。

-时间复杂度为O(nlogn)(排序),但题目要求O(n),可改为使用哈希表实现O(n)时间复杂度:

python

defcount_unique_numbers(nums):

returnlen(set(nums))

2.数据结构题(6分)

题目:

设计一个LRU(LeastRecentlyUsed)缓存,支持get和put操作。要求:

-get(key):返回键对应的值,并更新该键为最近使用。

-put(key,value):如果缓存已满,则删除最久未使用的键,再插入新键值对。

-使用双向链表和哈希表实现,时间复杂度均为O(1)。

答案:

python

classDLinkedNode:

def__init__(self,key=0,value=0):

self.key=key

self.value=value

self.prev=None

self.next=None

classLRUCache:

def__init__(self,capacity:int):

self.capacity=capacity

self.cache={}

self.head,self.tail=DLinkedNode(),DLinkedNode()

self.head.next=self.tail

self.tail.prev=self.head

def_add_node(self,node):

node.prev=self.head

node.next=self.head.next

self.head.next.prev=node

self.head.next=node

def_remove_node(self,node):

prev_node=node.prev

next_node=node.next

prev_node.next=next_node

next_node.prev=prev_node

def_move_to_head(self,node):

self._remove_node(node)

self._add_node(node)

def_pop_tail(self):

res=self.tail.prev

self._remove_node(res)

returnres

defget(self,key:int)-int:

node=self.cache.get(key,None)

ifnotnode:

return-1

self._move_to_head(node)

returnnode.value

defput(self,key:int,value:int)-None:

node=self.cache.get(key)

ifnotnode:

newNode=DLinkedNode(key,value)

self.cache[key]=newNode

self._add_node(newNode)

iflen(self.cache)self.capacity:

tail=self._pop_tail()

delself.cache[tail.key]

else:

node.value=value

self._move_to_head(node)

示例使用

cache=LRUCache(2)

cache.put(1,1)

cache.put(2,2)

print(cache.get(1))#返回1

cache.put(3,3)#去除键

文档评论(0)

1亿VIP精品文档

相关文档