阿里巴工程师高级面试题及答案.docxVIP

  • 0
  • 0
  • 约5.99千字
  • 约 15页
  • 2026-01-28 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年阿里巴工程师高级面试题及答案

一、编程题(共3题,每题20分,总分60分)

题目1(20分):

编写一个函数,实现将一个32位无符号整数的二进制表示翻转,并返回翻转后的整数。例如,输入`1234`,二进制表示为`00000000000000000000000000010010`,翻转后为`00000000000000000000000010001000`,输出为`8`。

答案与解析:

python

defreverse_bits(n:int)-int:

result=0

for_inrange(32):

result=(result1)|(n1)

n=1

returnresult0xFFFFFFFF

解析:

1.使用位操作逐位翻转:通过循环32次,每次将`result`左移一位,并与`n`的最低位进行或操作,实现翻转。

2.右移`n`一位,逐步处理更高位。

3.最后使用`0xFFFFFFFF`(32个1)进行位掩码,确保结果为32位无符号整数。

题目2(20分):

给定一个字符串`s`,其中只包含字母和数字,请找出其中最长的“平衡子字符串”。平衡子字符串指包含相同数量字母和数字的子字符串。例如,`a1b2c3`的最长平衡子字符串为`a1b2c3`。

答案与解析:

python

deflongest_balanced_substring(s:str)-str:

balance=0

max_len=0

start=0

balance_map={0:-1}

fori,charinenumerate(s):

ifchar.isalpha():

balance+=1

elifchar.isdigit():

balance-=1

ifbalanceinbalance_map:

current_len=i-balance_map[balance]

ifcurrent_lenmax_len:

max_len=current_len

start=balance_map[balance]+1

else:

balance_map[balance]=i

returns[start:start+max_len]

解析:

1.使用`balance`变量记录字母和数字的差值:字母为`+1`,数字为`-1`。

2.使用`balance_map`记录每个`balance`第一次出现的位置,初始为`{0:-1}`(表示空字符串前)。

3.当`balance`重复出现时,表示当前子字符串平衡,计算长度并更新最大值。

4.最终返回最长平衡子字符串。

题目3(20分):

设计一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。缓存容量为`capacity`,超出容量时删除最久未使用的项。例如,容量为`2`,`put(1,1)`,`put(2,2)`,`get(1)`返回`1`,`put(3,3)`会删除`2`,`get(2)`返回`-1`。

答案与解析:

python

classLRUCache:

def__init__(self,capacity:int):

self.capacity=capacity

self.cache={}

self.order=[]

defget(self,key:int)-int:

ifkeyinself.cache:

self.order.remove(key)

self.order.append(key)

returnself.cache[key]

return-1

defput(self,key:int,value:int)-None:

ifkeyinself.cache:

self.order.remove(key)

eliflen(self.cache)=self.capacity:

oldest_key=self.order.pop(0)

delself.cache[oldest_key]

self.cache[key]=value

self.order.append(key)

解析:

1.使用字典`cache`存储键值对,列表`order`记录使用顺序。

2.`get`操作:若键存在,移动到`order`末尾(表示最近使用),返回值。

3.`put`操作:若键已存在,更新值并移动到末尾;若超出容量,删除`order`第一个元素(最久未使用)并删除对应缓存。

4.保持`order`始终表示使用顺序,确保L

您可能关注的文档

文档评论(0)

1亿VIP精品文档

相关文档