2026年腾讯技术部门面试技巧及常见问题答案.docxVIP

  • 1
  • 0
  • 约7.4千字
  • 约 21页
  • 2026-01-12 发布于福建
  • 举报

2026年腾讯技术部门面试技巧及常见问题答案.docx

第PAGE页共NUMPAGES页

2026年腾讯技术部门面试技巧及常见问题答案

一、编程能力测试(共5题,每题10分,总分50分)

1.题目:

编写一个函数,实现快速排序算法。输入一个无序数组,输出排序后的数组。要求在函数中处理递归调用和基准选择(例如选择第一个元素作为基准)。

答案:

python

defquick_sort(arr):

iflen(arr)=1:

returnarr

pivot=arr[0]

left=[xforxinarr[1:]ifx=pivot]

right=[xforxinarr[1:]ifxpivot]

returnquick_sort(left)+[pivot]+quick_sort(right)

解析:

快速排序的核心是分治思想,通过选择基准元素将数组分成小于和大于两部分,然后递归排序子数组。上述代码选择第一个元素作为基准,递归处理左右子数组,最后合并结果。时间复杂度为O(nlogn),空间复杂度为O(logn)。

2.题目:

实现一个LRU(最近最少使用)缓存,支持get和put操作。要求用哈希表和双向链表实现,保证get和put操作的时间复杂度为O(1)。

答案:

python

classListNode:

def__init__(self,key=0,value=0,prev=None,next=None):

self.key=key

self.value=value

self.prev=prev

self.next=next

classLRUCache:

def__init__(self,capacity:int):

self.capacity=capacity

self.cache={}

self.head=ListNode()

self.tail=ListNode()

self.head.next=self.tail

self.tail.prev=self.head

def_add_node(self,node:ListNode):

node.prev=self.head

node.next=self.head.next

self.head.next.prev=node

self.head.next=node

def_remove_node(self,node:ListNode):

prev_node=node.prev

next_node=node.next

prev_node.next=next_node

next_node.prev=prev_node

def_move_to_head(self,node:ListNode):

self._remove_node(node)

self._add_node(node)

def_pop_tail(self)-ListNode:

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=ListNode(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)

解析:

LRU缓存的核心是通过双向链表和哈希表实现。双向链表维护访问顺序,头节点表示最近访问,尾节点表示最久未访问。哈希表存储键值对,通过O(1)时间查找到对应节点。get操作将节点移至头部,put操作插入新节点或更新现有节点,若超出容量则删除尾节点。

3.题目:

编写一个函数,实现二叉树的层序遍历(按从上到下、从左到右的顺序)。要求用队列实现,并返回遍历结果列表。

答案:

python

fromcollectionsimportdeque

clas

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档