2026年百度资深软件工程师面试问题解析.docxVIP

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

2026年百度资深软件工程师面试问题解析.docx

第PAGE页共NUMPAGES页

2026年百度资深软件工程师面试问题解析

一、编程基础与数据结构(共5题,每题10分,总分50分)

1.题目:

请实现一个函数,输入一个非负整数`n`,返回`n`的二进制表示中`1`的个数。要求不使用内置函数,时间复杂度为O(1)。

答案:

cpp

intcountOnes(intn){

intcount=0;

while(n!=0){

count+=n1;

n=1;

}

returncount;

}

解析:

该方法利用位运算技巧,通过`n1`获取最低位的`1`或`0`,然后右移一位继续统计。时间复杂度为O(1)是基于二进制位数固定(32位或64位)的假设,实际为O(logn)。

2.题目:

给定一个链表,判断其是否为回文链表。要求空间复杂度为O(1)。

答案:

cpp

boolisPalindrome(ListNodehead){

if(!head)returntrue;

//找到中点

ListNodefast=head,slow=head;

while(fast-nextfast-next-next){

fast=fast-next-next;

slow=slow-next;

}

//反转后半部分

ListNodeprev=nullptr,curr=slow;

while(curr){

ListNodenext=curr-next;

curr-next=prev;

prev=curr;

curr=next;

}

//对比前后半部分

ListNodep1=head,p2=prev;

while(p2){

if(p1-val!=p2-val)returnfalse;

p1=p1-next;

p2=p2-next;

}

returntrue;

}

解析:

方法分为三步:①找到中点;②反转后半部分;③对比前后半部分。空间复杂度为O(1)通过原地反转实现。

3.题目:

实现一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作,容量为`capacity`。

答案:

cpp

classLRUCache{

private:

unordered_mapint,pairint,ListNodecache;

ListNodehead,tail;

intcapacity;

public:

LRUCache(intcapacity):capacity(capacity){

head.next=tail;

tail.prev=head;

}

intget(intkey){

autoit=cache.find(key);

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

moveToHead(it-second.second);

returnit-second.first;

}

voidput(intkey,intvalue){

if(cache.find(key)!=cache.end()){

cache[key].first=value;

moveToHead(cache[key].second);

}else{

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

cache.erase(tail.prev-key);

removeNode(tail.prev);

}

ListNodenewNode;

cache[key]={value,newNode};

addNode(newNode);

}

}

private:

voidmoveToHead(ListNodenode){

removeNode(node);

addNode(node);

}

voidaddNode(ListNodenode){

node-prev=head;

node-next=head.next;

head.next-prev=node;

head.next=node;

}

voidremoveNode(ListNodenode){

node-prev-next=node-next;

node-next-prev=node-prev;

}

};

解析:

使用双向链表+哈希表实现。链表维护最近使用顺序,哈希表实现O(1)查找。`get`操作将元素移至头部,`put`操作先判断是否存在,若超出容量则删除尾部元素。

4.题目:

给定一个

文档评论(0)

1亿VIP精品文档

相关文档