- 2
- 0
- 约4.57千字
- 约 14页
- 2026-01-31 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年网易游戏开发工程师面试题与解答
一、编程基础(5题,每题10分,共50分)
1.题目:
请编写一个函数,实现二叉树的深度优先遍历(前序遍历),并返回遍历结果列表。假设二叉树节点定义如下:
python
classTreeNode:
def__init__(self,val=0,left=None,right=None):
self.val=val
self.left=left
self.right=right
示例输入:
树的结构:
1
/\
23
/\
45
预期输出:`[1,2,4,5,3]`
答案与解析:
python
defpreorder_traversal(root):
ifnotroot:
return[]
result=[]
stack=[root]
whilestack:
node=stack.pop()
result.append(node.val)
ifnode.right:
stack.append(node.right)
ifnode.left:
stack.append(node.left)
returnresult
解析:
前序遍历的顺序是“根-左-右”,使用栈实现时,先访问当前节点,然后右子节点先入栈,左子节点后入栈,确保左子节点先被访问。
2.题目:
给定一个字符串,请判断其是否为有效的括号组合(只考虑`()`、`[]`、`{}`)。
示例输入:`({[]})`
预期输出:`True`
答案与解析:
python
defisValid(s):
stack=[]
mapping={):(,]:[,}:{}
forcharins:
ifcharinmapping:
top_element=stack.pop()ifstackelse#
ifmapping[char]!=top_element:
returnFalse
else:
stack.append(char)
returnnotstack
解析:
使用栈匹配括号,左括号入栈,右括号时与栈顶比较,若不匹配则返回`False`,最后栈为空则有效。
3.题目:
实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。缓存容量为`capacity`。
示例输入:
LRUCache=LRUCache(2)
LRUCache.put(1,1)
LRUCache.put(2,2)
LRUCache.get(1)//返回1
LRUCache.put(3,3)//去除键2
LRUCache.get(2)//返回-1(未找到)
预期输出:`1,-1`
答案与解析:
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`时若超出容量则删除最久未使用节点。
4.题目:
请编写一个函数,找出数组中重复次数超过`n/2`的元素(假设数组非空且存在这样的元素)。
示例输入:`[3,2,3,1,3,3,3]`
预期输出:`3`
答案与解析:
python
defmajorityElement(nums):
count=0
candidate=None
fornuminnums:
ifcount==0:
candidate=num
count+=(1ifnum==candidateelse-
原创力文档

文档评论(0)