2026年程序员代码面试题与解答大全.docxVIP

  • 0
  • 0
  • 约7.14千字
  • 约 20页
  • 2026-01-05 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年程序员代码面试题与解答大全

一、编程基础(共5题,每题10分)

1.题目:

编写一个函数,判断一个字符串是否是回文字符串。例如,abba和racecar都是回文字符串,而hello不是。

答案:

python

defis_palindrome(s:str)-bool:

s=.join(s.split()).lower()#去除空格并转为小写

returns==s[::-1]

解析:

-首先去除字符串中的空格并统一为小写,以忽略大小写和空格的影响。

-然后通过切片`s[::-1]`反转字符串,若反转后与原字符串相同,则为回文。

2.题目:

给定一个数组,返回其中所有重复的元素。要求时间复杂度为O(n),空间复杂度为O(1)。

答案:

python

deffind_duplicates(nums:list)-list:

duplicates=[]

fornuminnums:

index=abs(num)-1#将元素映射到索引

ifnums[index]0:

duplicates.append(abs(num))

else:

nums[index]=-nums[index]#标记已访问

returnduplicates

解析:

-利用数组索引作为标记,将元素映射到其对应的索引位置。

-若某个索引对应的值已经是负数,说明该元素重复,直接加入结果。

-时间复杂度为O(n),空间复杂度为O(1),满足要求。

3.题目:

实现一个LRU(最近最少使用)缓存,支持get和put操作。

答案:

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=self.order.pop(0)

delself.cache[oldest]

self.cache[key]=value

self.order.append(key)

解析:

-使用哈希表存储键值对,双向链表维护访问顺序。

-get操作时,将访问的键移动到链表末尾。

-put操作时,若缓存已满,则删除最久未使用的键。

4.题目:

给定一个二叉树,返回其最大深度。

答案:

python

classTreeNode:

def__init__(self,val=0,left=None,right=None):

self.val=val

self.left=left

self.right=right

defmax_depth(root:TreeNode)-int:

ifnotroot:

return0

return1+max(max_depth(root.left),max_depth(root.right))

解析:

-递归遍历二叉树,每次深度加1,取左右子树的最大深度。

-时间复杂度为O(n),n为节点数。

5.题目:

实现快速排序算法。

答案:

python

defquick_sort(arr:list)-list:

iflen(arr)=1:

returnarr

pivot=arr[len(arr)//2]

left=[xforxinarrifxpivot]

middle=[xforxinarrifx==pivot]

right=[xforxinarrifxpivot]

returnquick_sort(left)+middle+quick_sort(right)

解析:

-选择基准值(pivot),将数组分为小于、等于、大于三部分。

-递归对左右部分排序,合并后返回。

二、算法与数据结构(共5题,每题10分)

6.题目:

给定一个无序数组,找到其中第k大的元素。

答案:

python

de

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档