2026年腾讯人工智能工程师面试题及答案参考.docxVIP

  • 1
  • 0
  • 约6.03千字
  • 约 16页
  • 2026-01-05 发布于福建
  • 举报

2026年腾讯人工智能工程师面试题及答案参考.docx

第PAGE页共NUMPAGES页

2026年腾讯人工智能工程师面试题及答案参考

一、编程题(3题,每题20分,共60分)

1.题目(20分):

实现一个函数`top_k_frequent(nums,k)`,输入一个整数数组`nums`和一个整数`k`,返回`nums`中出现频率最高的`k`个元素。要求不使用排序,时间复杂度优于O(nlogn)。

示例:

输入:`nums=[1,1,1,2,2,3],k=2`

输出:`[1,2]`

答案:

python

fromcollectionsimportCounter

deftop_k_frequent(nums,k):

count=Counter(nums)

bucket=[[]for_inrange(len(nums)+1)]

fornum,freqincount.items():

bucket[freq].append(num)

result=[]

foriinrange(len(bucket)-1,0,-1):

fornuminbucket[i]:

result.append(num)

iflen(result)==k:

returnresult

解析:

-使用`Counter`统计频率,时间复杂度O(n)。

-建立`bucket`数组,索引为频率,值为该频率对应的数字列表。

-从高频率开始遍历`bucket`,按需添加元素至结果,直到返回`k`个高频元素。

-时间复杂度O(n),空间复杂度O(n)。

2.题目(20分):

给定一个链表,判断其是否为回文链表。不能使用额外空间,时间复杂度O(n)。

示例:

输入:`1-2-2-1`

输出:`True`

答案:

python

classListNode:

def__init__(self,val=0,next=None):

self.val=val

self.next=next

defis_palindrome(head):

ifnotheadornothead.next:

returnTrue

找到中点

slow=head

fast=head

whilefast.nextandfast.next.next:

slow=slow.next

fast=fast.next.next

反转后半部分

prev=None

whileslow:

temp=slow.next

slow.next=prev

prev=slow

slow=temp

对比前后半部分

left,right=head,prev

whileright:#只需对比到后半部分结束

ifleft.val!=right.val:

returnFalse

left=left.next

right=right.next

returnTrue

解析:

-使用快慢指针找到链表的中点。

-反转后半部分链表。

-对比前半部分和反转后的后半部分是否相同。

-时间复杂度O(n),空间复杂度O(1)。

3.题目(20分):

实现一个LRU(LeastRecentlyUsed)缓存机制,支持`get`和`put`操作。`get(key)`返回键对应的值,若不存在返回-1;`put(key,value)`插入或更新键值对,当缓存容量满时,删除最久未使用的键。

示例:

LRU缓存容量为2:

`put(1,1)`

`put(2,2)`

`get(1)`→返回1

`put(3,3)`→假设容量满,删除键2

`get(2)`→返回-1

答案:

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:

o

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档