2026年阿里巴技术部门面试题详解与答案.docxVIP

  • 0
  • 0
  • 约6.61千字
  • 约 19页
  • 2026-02-09 发布于福建
  • 举报

2026年阿里巴技术部门面试题详解与答案.docx

第PAGE页共NUMPAGES页

2026年阿里巴技术部门面试题详解与答案

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

1.题目:

实现一个函数,输入一个正整数`n`,返回`n`的汉诺塔移动步骤。例如,`n=2`时,输出应为`ABACBCCBAB`,其中`A`、`B`、`C`代表三根柱子。

答案与解析:

python

defhanoi_steps(n):

defhelper(n,source,target,auxiliary):

ifn==1:

steps.append(f{source}{target})

return

helper(n-1,source,auxiliary,target)

steps.append(f{source}{target})

helper(n-1,auxiliary,target,source)

steps=[]

helper(n,A,C,B)

return.join(steps)

示例:n=2

print(hanoi_steps(2))#输出:ABACBCCBAB

解析:

汉诺塔问题采用递归解法,每次移动`n-1`个盘到辅助柱,再移动最大的盘到目标柱,最后将`n-1`个盘从辅助柱移动到目标柱。输出用`f-string`拼接移动步骤,时间复杂度O(2^n)。

2.题目:

给定一个包含重复数字的数组,返回所有不重复的全排列。例如,`[1,1,2]`的输出应为`[[1,1,2],[1,2,1],[2,1,1]]`。

答案与解析:

python

defpermute_unique(nums):

defbacktrack(path,used,res):

iflen(path)==len(nums):

res.append(path.copy())

return

foriinrange(len(nums)):

ifused[i]:

continue

ifi0andnums[i]==nums[i-1]andnotused[i-1]:

continue

used[i]=True

path.append(nums[i])

backtrack(path,used,res)

path.pop()

used[i]=False

nums.sort()

res,used=[],[False]len(nums)

backtrack([],used,res)

returnres

示例:[1,1,2]

print(permute_unique([1,1,2]))#输出:[[1,1,2],[1,2,1],[2,1,1]]

解析:

通过排序避免重复排列,使用`used`数组记录已使用元素。若当前数字与前一个数字相同且前一个未使用,则跳过以避免重复。时间复杂度O(n!).

3.题目:

实现LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。例如:

python

lru=LRUCache(2)

lru.put(1,1)

lru.put(2,2)

lru.get(1)#返回1

lru.put(3,3)#去除键2

lru.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:

oldest=self.order.pop(0)

delself.cache[oldest]

self.cache[key]=value

self.order.append(key)

示例

lru=LRUCache(2)

lru.put(1,1)

lru.put(2,2)

print(lru.get(1))#输出:1

lru.put(3,3)

print(lru.get(2))

文档评论(0)

1亿VIP精品文档

相关文档