- 1
- 0
- 约8.46千字
- 约 22页
- 2026-02-26 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年百度AI部门技术主管面试题集及答案解析
一、编程能力测试(5题,每题20分)
1.题目(20分):
编写一个Python函数,实现快速排序算法。输入为一个无序的整数列表,输出为按升序排列的列表。请展示代码,并解释时间复杂度和空间复杂度。
答案解析:
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(nlogn),随机选择枢轴时。
-最坏情况:O(n2),当枢轴选择为最大或最小值时(可通过随机化优化)。
空间复杂度:
-O(logn),递归调用栈的深度。
-辅助空间:O(n),用于存储左右子列表。
2.题目(20分):
给定一个字符串,编写一个函数判断其是否为回文串(忽略大小写和非字母字符)。例如,`Aman,aplan,acanal:Panama`应返回`True`。
答案解析:
python
defis_palindrome(s):
s=.join(c.lower()forcinsifc.isalnum())
returns==s[::-1]
3.题目(20分):
实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。缓存容量为固定值`capacity`。要求:
-`get(key)`:返回键对应的值,若不存在返回-1。
-`put(key,value)`:插入或更新键值对,若超出容量则删除最久未使用的项。
答案解析:
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)
4.题目(20分):
设计一个算法,找出数组中第k个最大的元素。不要求完全排序,要求时间复杂度为O(n)。
答案解析:
python
deffind_kth_largest(nums,k):
defpartition(left,right,pivot_index):
pivot=nums[pivot_index]
nums[pivot_index],nums[right]=nums[right],nums[pivot_index]
store_index=left
foriinrange(left,right):
ifnums[i]pivot:
nums[store_index],nums[i]=nums[i],nums[store_index]
store_index+=1
nums[right],nums[store_index]=nums[store_index],nums[right]
returnstore_index
left,right=0,len(nums)-1
whileTrue:
pivot_index=partition(left,right,left)
ifpivot_index==k-1:
returnnums[pivot_index]
elifpivot_indexk-1:
right=
原创力文档

文档评论(0)