2026年华为技术部主管面试题集及解答.docxVIP

  • 0
  • 0
  • 约6.29千字
  • 约 17页
  • 2026-03-05 发布于福建
  • 举报

2026年华为技术部主管面试题集及解答.docx

第PAGE页共NUMPAGES页

2026年华为技术部主管面试题集及解答

一、编程与算法(5题,每题10分,共50分)

1.题目:

实现一个函数,输入一个整数数组,返回数组中所有可能的子集。例如,输入`[1,2,3]`,输出`[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]`。

答案:

python

defsubsets(nums):

result=[]

subset=[]

defbacktrack(index):

result.append(subset.copy())

foriinrange(index,len(nums)):

subset.append(nums[i])

backtrack(i+1)

subset.pop()

backtrack(0)

returnresult

测试

print(subsets([1,2,3]))

解析:

使用回溯算法,通过递归构建所有可能的子集。每次选择一个元素加入当前子集,然后继续递归;不选择时跳过,继续递归。最终所有路径的组合即为所有子集。

2.题目:

给定一个包含`n`个节点的无向图,节点编号从`0`到`n-1`。请判断该图是否是二分图(即可以将节点分成两个集合,使得每条边的两个节点属于不同集合)。

答案:

python

fromcollectionsimportdeque

defis_bipartite(graph):

color={}

defbfs(node):

queue=deque([node])

color[node]=0

whilequeue:

current=queue.popleft()

forneighboringraph[current]:

ifneighborincolor:

ifcolor[neighbor]==color[current]:

returnFalse

else:

color[neighbor]=1-color[current]

queue.append(neighbor)

returnTrue

fornodeinrange(len(graph)):

ifnodenotincolor:

ifnotbfs(node):

returnFalse

returnTrue

测试

print(is_bipartite([[1,3],[0,2],[0,2],[0,1]]))#True

print(is_bipartite([[1,2,3],[0,2],[0,1],[0]]))#False

解析:

使用BFS遍历图,为每个节点分配颜色(0或1)。对于每个未访问的节点,从它开始BFS,并交替分配颜色。如果发现相邻节点颜色相同,则不是二分图。

3.题目:

实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。`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)

测试

lru=LRUCache(2)

lru.put(1,1)

lru.put(2,2)

print(lru.get(1))#1

lru.put(3,3)#去除键2

print(lru.get(2))#-1

解析:

使用哈希表存储键值对,维护一个双向链表记录访问顺序。`get`操作时将键移到链表末尾;`

文档评论(0)

1亿VIP精品文档

相关文档