高级工程师面试题含答案.docxVIP

  • 0
  • 0
  • 约6.91千字
  • 约 20页
  • 2026-02-12 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年高级工程师面试题含答案

一、编程实现题(共3题,每题20分)

题目1(Java):

问题描述:

实现一个简单的LRU(LeastRecentlyUsed)缓存淘汰算法,要求支持以下功能:

1.支持自定义缓存容量。

2.提供`get(key)`和`put(key,value)`接口,返回值分别为查找到的值或`-1`(未找到时)。

3.使用Java语言实现,需考虑线程安全。

示例:

java

LRUCachecache=newLRUCache(2);

cache.put(1,1);

cache.put(2,2);

System.out.println(cache.get(1));//返回1

cache.put(3,3);//去除键2

System.out.println(cache.get(2));//返回-1

cache.put(4,4);//去除键1

System.out.println(cache.get(1));//返回-1

System.out.println(cache.get(3));//返回3

System.out.println(cache.get(4));//返回4

答案:

java

importjava.util.HashMap;

importjava.util.Map;

publicclassLRUCacheK,V{

privatefinalintcapacity;

privatefinalMapK,Nodemap;

privateNodehead,tail;

privatestaticclassNodeK,V{

Kkey;

Vvalue;

NodeK,Vprev;

NodeK,Vnext;

Node(Kkey,Vvalue){

this.key=key;

this.value=value;

}

}

publicLRUCache(intcapacity){

this.capacity=capacity;

map=newHashMap();

head=newNode(null,null);

tail=newNode(null,null);

head.next=tail;

tail.prev=head;

}

publicVget(Kkey){

synchronized(this){

NodeK,Vnode=map.get(key);

if(node==null)returnnull;

moveToHead(node);

returnnode.value;

}

}

publicvoidput(Kkey,Vvalue){

synchronized(this){

NodeK,Vnode=map.get(key);

if(node!=null){

node.value=value;

moveToHead(node);

}else{

NodeK,VnewNode=newNode(key,value);

map.put(key,newNode);

addNode(newNode);

if(map.size()capacity){

removeTail();

}

}

}

}

privatevoidaddNode(NodeK,Vnode){

node.prev=head;

node.next=head.next;

head.next.prev=node;

head.next=node;

}

privatevoidremoveNode(NodeK,Vnode){

node.prev.next=node.next;

node.next.prev=node.prev;

}

privatevoidmoveToHead(NodeK,Vnode){

removeNode(node);

addNode(node);

}

privatevoidremoveTail(){

NodeK,VtailPrev=tail.prev;

removeNode(tailPrev);

map.remove(tailPrev.key);

}

}

解析:

1.LRU原理:通过双向链表维护最近访问的顺序,哈希表实现O(1)时间复杂度的查找。

2.线程安全:使用`synchronized`块锁定整个方法,避免多线程并发时数据不一致。

3.关键操作:

-`get()`:命中

文档评论(0)

1亿VIP精品文档

相关文档