- 1
- 0
- 约8.06千字
- 约 25页
- 2026-01-15 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年华为研发工程师面试题及答案详解
一、编程语言与数据结构(共5题,每题10分,总分50分)
1.题目:
请用C++实现一个函数,输入一个无重复元素的整数数组,返回其所有可能的全排列。要求不使用递归,并说明时间复杂度。
答案与解析:
cpp
includevector
includealgorithm
std::vectorstd::vectorintpermute(std::vectorintnums){
std::vectorstd::vectorintresults;
std::sort(nums.begin(),nums.end());
std::vectorboolused(nums.size(),false);
std::vectorintpath;
std::functionvoid()backtrack=[](){
if(path.size()==nums.size()){
results.emplace_back(path);
return;
}
for(inti=0;inums.size();++i){
if(used[i])continue;
if(i0nums[i]==nums[i-1]!used[i-1])continue;
used[i]=true;
path.push_back(nums[i]);
backtrack();
path.pop_back();
used[i]=false;
}
};
backtrack();
returnresults;
}
解析:
-使用回溯算法(非递归形式),通过`used`数组记录已使用元素,`path`记录当前排列。
-时间复杂度:O(n!×n),因为全排列有n!种,每次选择需要O(n)时间。
-去重技巧:相邻元素相同且前一个未使用时跳过,避免重复排列。
2.题目:
请用Java实现一个LRU(LeastRecentlyUsed)缓存,支持get和put操作,要求空间复杂度为O(1)。
答案与解析:
java
importjava.util.HashMap;
importjava.util.Map;
classLRUCache{
privateMapInteger,Nodecache=newHashMap();
privateNodehead,tail;
privateintcapacity;
classNode{
intkey;
intvalue;
Nodeprev,next;
}
publicLRUCache(intcapacity){
this.capacity=capacity;
head=newNode();
tail=newNode();
head.next=tail;
tail.prev=head;
}
publicintget(intkey){
Nodenode=cache.get(key);
if(node==null)return-1;
moveToHead(node);
returnnode.value;
}
publicvoidput(intkey,intvalue){
Nodenode=cache.get(key);
if(node!=null){
node.value=value;
moveToHead(node);
}else{
NodenewNode=newNode();
newNode.key=key;
newNode.value=value;
cache.put(key,newNode);
addToHead(newNode);
if(cache.size()capacity){
NodetoDel=tail.prev;
removeNode(toDel);
cache.remove(toDel.key);
}
}
}
privatevoidmoveToHead(Nodenode){
removeNode(node);
addToHead(node);
}
privatevoidaddToHead(Nodenode){
node.prev=head;
node.next=head.next;
head.next.prev=node;
head.next=node;
}
privatevoidremoveNode(Nodenode){
node.prev.nex
您可能关注的文档
最近下载
- 推进教育、科技、人才一体化发行动计划.docx
- 24J306国家建筑标准设计图集.docx
- 沟通的力量:护理人文案例集锦.pptx VIP
- 2023-2024学年安徽省宣城市七年级(上)期末语文试卷(含详细答案解析).docx VIP
- 护理人文关怀实践案例与反思.docx VIP
- 《大学物理》2024-2025学年第一学期期末试卷及答案.docx VIP
- 橡胶和塑料制品加工系统粉尘防爆安全规范.docx VIP
- AQ_4232-2013 塑料生产系统粉尘防爆规范.pdf VIP
- 2024年江苏中职职教高考文化统考语文试卷真题(含答案详解).docx VIP
- GB50469-2016 橡胶工厂环境保护设计规范.pdf VIP
原创力文档

文档评论(0)