微软后端开发工程师面试题库及答案详解.docxVIP

  • 1
  • 0
  • 约3.75千字
  • 约 11页
  • 2025-12-08 发布于福建
  • 举报

微软后端开发工程师面试题库及答案详解.docx

第PAGE页共NUMPAGES页

微软后端开发工程师面试题库及答案详解

一、编程题(共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)

示例

print(quick_sort([3,6,8,10,1,2,1]))

答案解析:

快速排序通过分治法实现,选择一个基准值(pivot),将数组分为小于、等于、大于三部分,再递归排序左右子数组。时间复杂度O(nlogn),最坏情况O(n2)。

2.编写一个函数,实现LRU(最近最少使用)缓存。

python

classLRUCache:

def__init__(self,capacity:int):

self.cache={}

self.capacity=capacity

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通过双向链表和哈希表实现,get时移动元素到链表末尾,put时先删除最久未使用元素,再添加新元素。时间复杂度O(1)。

3.编写一个函数,实现二叉树的深度优先遍历(前序、中序、后序)。

python

classTreeNode:

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

self.val=val

self.left=left

self.right=right

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]

答案解析:

前序:根-左-右;中序:左-根-右;后序:左-右-根。递归实现简单,时间复杂度O(n)。

4.编写一个函数,实现字符串的URL解码。

python

defurl_decode(url:str)-str:

return.join([chr(int(part[1:],16))if%inpartelsepartforpartinurl.split(/)])

示例

print(url_decode(https%3A%2F%2F%2Fpath%3Fquery%3Dvalue))

答案解析:

URL解码将%xx转换为字符,如%3A→:。按/分割后处理每个部分。

5.编写一个函数,实现判断一个数是否为素数。

python

defis_prime(n:int)-bool:

ifn=1:

returnFalse

foriinrange(2,int(n0.5)+1):

ifn%i==0:

returnFalse

returnTrue

示例

print(is_prime(17))#True

print(

文档评论(0)

1亿VIP精品文档

相关文档