2026年腾讯云开发工程师面试题目.docxVIP

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

第PAGE页共NUMPAGES页

2026年腾讯云开发工程师面试题目

一、编程基础与算法(共5题,每题8分,总分40分)

1.题目:

请实现一个函数,输入一个正整数`n`,返回`n`的二进制表示中`1`的个数。要求不使用内置函数,时间复杂度尽可能低。

答案与解析:

答案:

python

defcount_bits(n):

count=0

whilen:

count+=n1

n=1

returncount

解析:

该方法利用位运算技巧,通过不断右移`n`并与`1`进行``操作,统计`1`的个数。时间复杂度为O(logn),优于直接遍历每一位的方法。

2.题目:

给定一个链表,判断链表是否存在环。如果存在,返回环的入口节点;否则返回`None`。

答案与解析:

答案:

python

classListNode:

def__init__(self,x):

self.val=x

self.next=None

defdetect_cycle(head):

ifnothead:

returnNone

slow=head

fast=head

whilefastandfast.next:

slow=slow.next

fast=fast.next.next

ifslow==fast:

slow=head

whileslow!=fast:

slow=slow.next

fast=fast.next

returnslow

returnNone

解析:

使用快慢指针法(Floyd判圈算法),若链表存在环,快慢指针最终会相遇;相遇后,将慢指针移动到头节点,再次以相同速度移动,相遇点即为环的入口。时间复杂度O(n),空间复杂度O(1)。

3.题目:

请实现一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。缓存容量为`capacity`。

答案与解析:

答案:

python

classLRUCache:

def__init__(self,capacity:int):

self.capacity=capacity

self.cache={}

self.head=Node(0,0)

self.tail=Node(0,0)

self.head.next=self.tail

self.tail.prev=self.head

classNode:

def__init__(self,key,value):

self.key=key

self.value=value

self.prev=None

self.next=None

defget(self,key:int)-int:

ifkeyinself.cache:

node=self.cache[key]

self._remove(node)

self._add(node)

returnnode.value

return-1

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

ifkeyinself.cache:

self._remove(self.cache[key])

node=self.Node(key,value)

self.cache[key]=node

self._add(node)

iflen(self.cache)self.capacity:

lru=self.tail.prev

self._remove(lru)

delself.cache[lru.key]

def_remove(self,node):

node.prev.next=node.next

node.next.prev=node.prev

def_add(self,node):

node.prev=self.head

node.next=self.head.next

self.head.next.prev=node

self.head.next=node

解析:

使用双向链表+哈希表实现。链表维护最近使用顺序,哈希表实现O(1)访问。`get`操作将节点移到头部,`put`操作先删除旧节点(若存在),再添加到头部并检查容量,若超出则删除尾部节点。

4.题目:

给定一个字符串`s`,找到最长的回文子串的长度。

答案与解析:

答案:

python

deflongest_palindrome(s:str)-int:

ifnots:

retu

文档评论(0)

1亿VIP精品文档

相关文档