2026年阿里巴技术岗位面试题集与解析.docxVIP

  • 0
  • 0
  • 约5.42千字
  • 约 16页
  • 2026-01-18 发布于福建
  • 举报

2026年阿里巴技术岗位面试题集与解析.docx

第PAGE页共NUMPAGES页

2026年阿里巴技术岗位面试题集与解析

编程能力测试(共5题,每题10分)

1.题目:

编写一个函数,实现快速排序算法,并分析其时间复杂度和空间复杂度。

答案:

python

defquick_sort(arr):

iflen(arr)=1:

returnarr

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

left=[xforxinarrifxpivot]

middle=[xforxinarrifx==pivot]

right=[xforxinarrifxpivot]

returnquick_sort(left)+middle+quick_sort(right)

时间复杂度:O(nlogn),最坏情况下为O(n^2)

空间复杂度:O(logn),递归栈空间

解析:

快速排序通过分治法实现排序,核心是选择一个基准值(pivot),将数组分为三部分:小于基准的、等于基准的、大于基准的。时间复杂度在平均和最优情况下为O(nlogn),但最坏情况下(如已排序数组)会退化到O(n^2)。空间复杂度主要来自递归栈,最坏情况下为O(n),但平均情况下为O(logn)。

2.题目:

实现一个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)

解析:

LRU缓存通过双向链表和哈希表实现。哈希表用于O(1)时间查找缓存,双向链表用于维护访问顺序。get操作将访问的键移到链表末尾,put操作在哈希表中插入或更新键值对,若超出容量则删除链表头部(最久未使用)的键。

3.题目:

给定一个字符串,判断它是否是有效的括号组合(如()、()[]{})。

答案:

python

defisValid(s:str)-bool:

stack=[]

mapping={):(,]:[,}:{}

forcharins:

ifcharinmapping:

top=stack.pop()ifstackelse#

ifmapping[char]!=top:

returnFalse

else:

stack.append(char)

returnnotstack

解析:

使用栈结构,遍历字符串:遇到左括号入栈,遇到右括号时栈顶应为对应左括号,否则无效。最后栈应为空。时间复杂度O(n),空间复杂度O(n)。

4.题目:

实现一个二叉树的深度优先遍历(前序、中序、后序)。

答案:

python

前序遍历

defpreorder(root):

ifnotroot:

return[]

return[root.val]+preorder(root.left)+preorder(root.right)

中序遍历

definorder(root):

ifnotroot:

return[]

returninorder(root.left)+[root.val]+inorder(root.right)

后序遍历

defpostorder(root):

ifnotroot:

return[]

returnpostorder(root.left)+postorder(root.right)+[root.val]

解析:

前序遍历先访问根节点,再左子树,最后右子树;中序遍历先左子树,再根节点,最后右子树;后序遍历先左子树,再右子树,最后根节点。递归实现简单,但栈实现可避免栈溢出。

5.

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档