2026年华为技术总监面试题集与解答.docxVIP

  • 0
  • 0
  • 约6.12千字
  • 约 19页
  • 2026-01-21 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年华为技术总监面试题集与解答

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

解析:

快速排序的时间复杂度为O(nlogn),最坏情况下为O(n2)。空间复杂度为O(logn),因为递归调用栈的深度决定了空间复杂度。代码中使用了分治法,将数组分为小于、等于和大于枢轴的三个部分,再递归排序。

2.题目:

给定一个字符串,判断是否是有效的括号组合(如()、()[]{})。可以假设只包含四种括号。

答案:

python

defisValid(s):

stack=[]

mapping={):(,]:[,}:{}

forcharins:

ifcharinmapping:

top_element=stack.pop()ifstackelse#

ifmapping[char]!=top_element:

returnFalse

else:

stack.append(char)

returnnotstack

解析:

使用栈来处理括号匹配问题。遍历字符串,遇到右括号时检查栈顶是否为对应的左括号,如果是则弹出,否则返回无效。最后栈应为空则有效。时间复杂度为O(n),空间复杂度为O(n)。

3.题目:

实现一个LRU(最近最少使用)缓存,支持get和put操作。缓存容量为固定值。

答案:

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_key=self.order.pop(0)

delself.cache[oldest_key]

self.cache[key]=value

self.order.append(key)

解析:

使用字典存储键值对,列表维护访问顺序。get操作时将键移到末尾表示最近使用,put操作时若超出容量则删除最旧的元素。时间复杂度为O(1)。

4.题目:

设计一个算法,找出数组中重复次数超过一半的元素。

答案:

python

defmajorityElement(nums):

count=0

candidate=None

fornuminnums:

ifcount==0:

candidate=num

count+=(1ifnum==candidateelse-1)

returncandidate

解析:

Boyer-Moore投票算法。维护一个候选者和计数器,遍历数组时调整计数器。最终候选者即为多数元素。时间复杂度为O(n),空间复杂度为O(1)。

5.题目:

实现一个函数,检查一个二叉树是否是平衡的(即左右子树高度差不超过1)。

答案:

python

classTreeNode:

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

self.val=val

self.left=left

self.right=right

defisBalanced(root):

defcheck(node):

ifnotnode:

return0,True

left_height,left_b

文档评论(0)

1亿VIP精品文档

相关文档