- 0
- 0
- 约6.61千字
- 约 19页
- 2026-02-09 发布于福建
- 举报
第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))
您可能关注的文档
- 2026年AI定制服务项目投资计划书.docx
- 2026年AI定制服务项目营销方案.docx
- 2026年AI定制营养项目公司成立分析报告.docx
- 2026年AI定制营养项目建议书.docx
- 2026年AI定制营养项目可行性研究报告.docx
- 2026年AI定制营养项目评估报告.docx
- 2026年AI定制营养项目商业计划书.docx
- 2026年AI定制营养项目投资计划书.docx
- 2026年AI定制营养项目营销方案.docx
- 2026年AI法庭文书辅助项目公司成立分析报告.docx
- 八年级语文下册na文言文阅读专练(二).pptx
- 2025年福建莆田秀屿区南日镇卫生院第一轮编外人员招聘2人笔试历年题库附答案解析.docx
- 八年级语文下册nb文言文阅读专练(一) (2).pptx
- 八年级语文下册n2 回延安 (5).pptx
- 2025年福建莆田秀屿区南日镇卫生院第一轮编外人员招聘2人笔试历年题库附答案解析.docx
- 2025年福建莆田市荔城区东洋中学代课教师招聘1人笔试试题附答案解析.docx
- 八年级语文下册nc文言文阅读专练(一) (3).pptx
- 2025年福建莆田市莆投智泊科技有限公司职业经理人招聘2人笔试历年题库附答案解析.docx
- 八年级语文下册ne写作 (2).pptx
- 2025年福建莆田市荔城区东洋中学代课教师招聘1人笔试备考题库附答案解析.docx
原创力文档

文档评论(0)