2026年微软技术团队面试常见问题及答案.docxVIP

  • 0
  • 0
  • 约5.56千字
  • 约 16页
  • 2026-03-10 发布于福建
  • 举报

2026年微软技术团队面试常见问题及答案.docx

第PAGE页共NUMPAGES页

2026年微软技术团队面试常见问题及答案

一、编程能力测试(共5题,每题20分)

1.题目:

实现一个函数,输入一个字符串,返回该字符串中所有唯一字符的列表(不区分大小写)。例如,输入`HelloWorld`,返回`[[H,e,W,r,d]]`。要求时间复杂度为O(n)。

答案:

python

defunique_chars(s):

fromcollectionsimportdefaultdict

count=defaultdict(int)

forcharins.lower():

count[char]+=1

return[[charforcharinsifcount[char.lower()]==1]]

解析:

-使用`defaultdict`统计每个字符的频率,忽略大小写。

-遍历字符串,仅保留频率为1的字符。

-最终返回嵌套列表,包含所有唯一字符。

2.题目:

实现快速排序算法(QuickSort),输入一个无序数组,返回排序后的数组。要求原地排序(不使用额外内存)。

答案:

python

defquick_sort(arr,low,high):

iflowhigh:

pivot=partition(arr,low,high)

quick_sort(arr,low,pivot-1)

quick_sort(arr,pivot+1,high)

defpartition(arr,low,high):

pivot=arr[high]

i=low-1

forjinrange(low,high):

ifarr[j]=pivot:

i+=1

arr[i],arr[j]=arr[j],arr[i]

arr[i+1],arr[high]=arr[high],arr[i+1]

returni+1

解析:

-选择最后一个元素作为基准(pivot)。

-将小于等于基准的元素移到基准左侧,大于基准的移到右侧。

-递归对左右子数组进行排序。

3.题目:

实现一个二叉树的中序遍历(In-orderTraversal),输入树的根节点,返回遍历结果的列表。要求使用递归和非递归两种方法。

答案:

递归方法:

python

definorder_recursive(root):

ifnotroot:

return[]

returninorder_recursive(root.left)+[root.val]+inorder_recursive(root.right)

非递归方法:

python

definorder_iterative(root):

stack,result=[],[]

current=root

whilestackorcurrent:

whilecurrent:

stack.append(current)

current=current.left

current=stack.pop()

result.append(current.val)

current=current.right

returnresult

解析:

-递归方法:左-根-右。

-非递归方法:使用栈模拟递归,先压左子树,再访问节点,最后右子树。

4.题目:

实现一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。输入键值对,`get`返回值或-1,`put`插入或更新键值对。要求时间复杂度为O(1)。

答案:

python

classLRUCache:

def__init__(self,capacity:int):

fromcollectionsimportOrderedDict

self.cache=OrderedDict()

self.capacity=capacity

defget(self,key:int)-int:

ifkeynotinself.cache:

return-1

self.cache.move_to_end(key)

returnself.cache[key]

defput(self,key:int,value:int)-None:

ifkeyinself.cache:

self.cache.move_to_end(key)

self.cache[key]=value

iflen(self.cache)self.capacity:

sel

文档评论(0)

1亿VIP精品文档

相关文档