京东游戏程序面试题集.docxVIP

  • 0
  • 0
  • 约6.09千字
  • 约 18页
  • 2026-01-26 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年京东游戏程序面试题集

一、编程基础(5题,每题10分,共50分)

1.题目:

请实现一个函数,输入一个整数数组,返回数组中所有可能的子集(不包含空集)。要求:不使用递归,时间复杂度尽可能低。

答案与解析:

cpp

includevector

usingnamespacestd;

classSolution{

public:

vectorvectorintsubsets(vectorintnums){

vectorvectorintresult;

vectorintpath;

result.push_back(path);

for(inti=0;inums.size();++i){

intsize=result.size();

for(intj=0;jsize;++j){

vectorintnewPath=result[j];

newPath.push_back(nums[i]);

result.push_back(newPath);

}

}

returnresult;

}

};

解析:

采用迭代法构建子集,每次遍历数组时,将当前数字添加到所有已有子集中,生成新的子集并加入结果中。时间复杂度为O(2^n),空间复杂度为O(n2^n),符合要求。

2.题目:

请实现一个LRU(LeastRecentlyUsed)缓存,支持get和put操作,要求get操作返回值为整数,put操作无返回值。缓存容量为固定值。

答案与解析:

cpp

includeunordered_map

includelist

classLRUCache{

private:

intcapacity;

unordered_mapint,listpairint,int::iteratorcache;

listpairint,intlruList;

public:

LRUCache(intcapacity_):capacity(capacity_){}

intget(intkey){

autoit=cache.find(key);

if(it==cache.end())return-1;

lruList.splice(lruList.begin(),lruList,it-second);

returnit-second-second;

}

voidput(intkey,intvalue){

autoit=cache.find(key);

if(it!=cache.end()){

lruList.splice(lruList.begin(),lruList,it-second);

it-second-second=value;

}else{

if(cache.size()==capacity){

intoldestKey=lruList.back().first;

cache.erase(oldestKey);

lruList.pop_back();

}

lruList.push_front({key,value});

cache[key]=lruList.begin();

}

}

};

解析:

使用双向链表和哈希表实现LRU缓存。双向链表存储最近使用的元素,哈希表提供O(1)的访问时间。get操作将元素移至链表头部,put操作先判断是否存在,若存在则更新并移动,若不存在则删除最旧的元素并添加新元素。

3.题目:

请实现一个函数,判断一个二叉树是否是完全二叉树。

答案与解析:

cpp

includequeue

structTreeNode{

intval;

TreeNodeleft;

TreeNoderight;

TreeNode(intx):val(x),left(nullptr),right(nullptr){}

};

boolisCompleteTree(TreeNoderoot){

if(!root)returntrue;

queueTreeNodeq;

q.push(root);

boolend=false;

while(!q.empty()){

TreeNodenode=q.front();

q.pop();

if(node){

if(end)returnfalse;

q.push(node-left);

q.push(node-right);

}else{

end=true;

}

}

returntrue;

}

解析:

层序遍历二叉树,若遇

文档评论(0)

1亿VIP精品文档

相关文档