- 4
- 0
- 约1.13万字
- 约 31页
- 2026-01-30 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年程序员高级面试题及应对策略
一、算法与数据结构(共5题,每题15分,总分75分)
1.题目:
实现一个LRU(最近最少使用)缓存,支持get和put操作。缓存容量为`capacity`,get和put操作的时间复杂度为O(1)。
答案与解析:
java
classLRUCache{
privateMapInteger,Nodemap;
privateNodehead,tail;
privateintcapacity;
classNode{
intkey,value;
Nodeprev,next;
}
publicLRUCache(intcapacity){
this.capacity=capacity;
map=newHashMap();
head=newNode();
tail=newNode();
head.next=tail;
tail.prev=head;
}
publicintget(intkey){
Nodenode=map.get(key);
if(node==null)return-1;
moveToHead(node);
returnnode.value;
}
publicvoidput(intkey,intvalue){
Nodenode=map.get(key);
if(node!=null){
node.value=value;
moveToHead(node);
}else{
NodenewNode=newNode();
newNode.key=key;
newNode.value=value;
map.put(key,newNode);
addToHead(newNode);
if(map.size()capacity){
NodetoRemove=removeTail();
map.remove(toRemove.key);
}
}
}
privatevoidaddToHead(Nodenode){
node.prev=head;
node.next=head.next;
head.next.prev=node;
head.next=node;
}
privatevoidremoveNode(Nodenode){
node.prev.next=node.next;
node.next.prev=node.prev;
}
privatevoidmoveToHead(Nodenode){
removeNode(node);
addToHead(node);
}
privateNoderemoveTail(){
Noderes=tail.prev;
removeNode(res);
returnres;
}
}
解析:
LRU缓存的核心是双向链表+哈希表。双向链表维护访问顺序,哈希表实现O(1)的get和put。get时将节点移到头部,put时若存在则更新并移动到头部,若不存在则新建节点并添加到头部,若超出容量则删除尾部节点。
2.题目:
给定一个包含重复元素的数组,找出所有不重复的三元组,使得三元组的和等于目标值`target`。
答案与解析:
java
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
publicclassThreeSum{
publicListListIntegerthreeSum(int[]nums,inttarget){
ListListIntegerres=newArrayList();
if(nums==null||nums.length3)returnres;
Arrays.sort(nums);
for(inti=0;inums.length-2;i++){
if(i0nums[i]==nums[i-1])continue;
intleft=i+1,right=nums.length-1;
while(leftright){
intsum=nums[i]+nums[left]+nums[right];
if(sum==target){
res.add(Arrays.asList(nums[i],nums[left],nums[right]));
whi
原创力文档

文档评论(0)