2026年阿里巴技术部门面试题及解析.docxVIP

  • 0
  • 0
  • 约5.26千字
  • 约 17页
  • 2026-01-11 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年阿里巴技术部门面试题及解析

一、编程基础与算法(共5题,每题10分,总分50分)

1.题目:

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

答案:

java

publicintcountOnes(intn){

intcount=0;

while(n!=0){

count+=(n1);

n=1;//无符号右移

}

returncount;

}

解析:

利用位运算,通过`n1`获取最低位的`0`或`1`,然后右移一位继续统计。无符号右移``确保负数也能正确处理。时间复杂度O(1)的前提是位数固定(32位或64位),实际面试中可能需要说明位数假设。

2.题目:

给定一个数组`nums`,返回其中第三大的数。如果不存在,返回最大的数。

答案:

java

publicintthirdMax(int[]nums){

Longmax1=Long.MIN_VALUE,max2=Long.MIN_VALUE,max3=Long.MIN_VALUE;

for(intnum:nums){

if(nummax1){

max3=max2;

max2=max1;

max1=num;

}elseif(nummax2num!=max1){

max3=max2;

max2=num;

}elseif(nummax3num!=max2num!=max1){

max3=num;

}

}

returnmax3==Long.MIN_VALUE?max1:max3;

}

解析:

使用三个变量记录前三大的数,遍历数组时依次更新。注意排除重复值,用`Long.MIN_VALUE`避免整数溢出。如果`max3`未更新,说明只有两个数,返回`max1`。

3.题目:

设计一个`LRUCache`(最近最少使用缓存),支持`get`和`put`操作。

答案:

java

classLRUCache{

privateintcapacity;

privateMapInteger,Nodecache;

privateNodehead,tail;

classNode{

intkey,value;

Nodeprev,next;

}

publicLRUCache(intcapacity){

this.capacity=capacity;

cache=newHashMap();

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){

NodetoRemove=tail.prev;

removeNode(toRemove);

cache.remove(toRemove.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.next=node.next;

node.n

文档评论(0)

1亿VIP精品文档

相关文档