- 0
- 0
- 约5.25千字
- 约 17页
- 2026-02-13 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年华为研发工程师面试技巧与问题解析
一、编程能力测试(共5题,每题10分,总分50分)
1.题目:
请实现一个函数,输入一个非负整数n,返回其二进制表示中1的个数。例如,输入5(二进制为101),返回2。
答案:
cpp
intcountOnes(intn){
intcount=0;
while(n){
count+=n1;
n=1;
}
returncount;
}
解析:
使用位运算高效统计1的个数。`n1`判断最低位是否为1,`n=1`将n右移一位。时间复杂度为O(logn),适合大数处理。
2.题目:
给定一个字符串,请将其反转,不使用额外空间。
答案:
cpp
voidreverseString(chars){
if(!s)return;
charleft=s;
charright=s+strlen(s)-1;
while(leftright){
swap(left,right);
left++;
right--;
}
}
解析:
双指针法从两端向中间交换字符,避免使用额外空间。时间复杂度为O(n),空间复杂度为O(1)。
3.题目:
实现一个LRU(最近最少使用)缓存,支持get和put操作。
答案:
cpp
classLRUCache{
private:
unordered_mapint,intcache;
listintkeys;
intcapacity;
public:
LRUCache(intcap):capacity(cap){}
intget(intkey){
autoit=cache.find(key);
if(it==cache.end())return-1;
keys.remove(key);
keys.push_front(key);
returnit-second;
}
voidput(intkey,intvalue){
autoit=cache.find(key);
if(it!=cache.end()){
keys.remove(key);
keys.push_front(key);
cache[key]=value;
}else{
if(cache.size()==capacity){
cache.erase(keys.back());
keys.pop_back();
}
keys.push_front(key);
cache[key]=value;
}
}
};
解析:
使用哈希表+双向链表实现。哈希表记录键值对,链表维护访问顺序。get操作将键移到头部,put操作先删除最久未使用的键。
4.题目:
给定一个链表,判断是否存在环,并返回入口节点。
答案:
cpp
ListNodedetectCycle(ListNodehead){
if(!head)returnnullptr;
ListNodeslow=head;
ListNodefast=head;
boolhasCycle=false;
while(fastfast-next){
slow=slow-next;
fast=fast-next-next;
if(slow==fast){
hasCycle=true;
break;
}
}
if(!hasCycle)returnnullptr;
slow=head;
while(slow!=fast){
slow=slow-next;
fast=fast-next;
}
returnslow;
}
解析:
快慢指针判断环,若相遇则存在环。继续移动慢指针至头部,与快指针再次相遇时即为入口节点。时间复杂度O(n),空间复杂度O(1)。
5.题目:
实现快速排序算法,要求原地排序。
答案:
cpp
voidquickSort(intarr,intleft,intright){
if(left=right)return;
intpivot=arr[left];
inti=left,j=right;
while(ij){
while(ijarr[j]=pivot)j--;
if(ij)arr[i++]=arr[j];
while(ijarr[i]=pivot)i++;
if(ij)arr[j--]=arr[i];
}
arr[i]=pivot;
quickSort(arr,
原创力文档

文档评论(0)