2026年京东工程师面试题及答案.docxVIP

  • 0
  • 0
  • 约4.07千字
  • 约 11页
  • 2026-02-10 发布于福建
  • 举报

第PAGE页共NUMPAGES页

2026年京东工程师面试题及答案

一、编程题(3题,每题15分,共45分)

1.题目(15分):

编写一个函数,实现将一个字符串中的所有大写字母转换为小写字母,所有小写字母转换为大写字母。其他字符保持不变。要求不使用内置的字符串反转或大小写转换函数,仅用循环和条件判断实现。

答案:

python

defswap_case(s:str)-str:

result=[]

forcharins:

ifa=char=z:

result.append(chr(ord(char)-32))#小写转大写

elifA=char=Z:

result.append(chr(ord(char)+32))#大写转小写

else:

result.append(char)

return.join(result)

示例

print(swap_case(HelloWorld!))#输出:hELLOwORLD!

解析:

-遍历字符串的每个字符,判断其是否为小写字母(`a=char=z`)或大写字母(`A=char=Z`)。

-小写字母通过减去32(ASCII码差值)转换为大写,大写字母通过加上32转换为小写。

-其他字符直接保留。

-最终用`join`将列表转换为字符串。

2.题目(15分):

实现一个LRU(LeastRecentlyUsed)缓存机制,支持以下操作:

-`get(key)`:获取键对应的值,如果键存在则返回值,并将该键标记为最近使用;如果键不存在返回-1。

-`put(key,value)`:插入或更新键值对。如果缓存已满(假设容量为固定值),则删除最久未使用的键。

答案:

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)

示例

cache=LRUCache(2)

cache.put(1,1)

cache.put(2,2)

print(cache.get(1))#返回1

cache.put(3,3)#去除键2

print(cache.get(2))#返回-1

解析:

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

-`get`操作:如果键存在,将其移动到`order`末尾(表示最近使用)。

-`put`操作:如果键已存在,更新值并移动到末尾;如果缓存已满,删除`order`第一个元素(最久未使用)并从`cache`中删除对应键。

3.题目(15分):

给定一个整数数组,返回所有和为特定目标值的三元组(不重复)。例如:输入`[1,2,3,4,5]`,目标值`9`,输出`[[1,2,6],[1,3,5],[2,3,4]]`。

答案:

python

defthree_sum(nums:List[int],target:int)-List[List[int]]:

nums.sort()

result=[]

n=len(nums)

foriinrange(n):

ifi0andnums[i]==nums[i-1]:

continue

left,right=i+1,n-1

whileleftright:

total=nums[i]+nums[left]+nums[right]

iftotal==target:

result.append([nums[i],nums[left],nums[right]])

whileleftrightand

文档评论(0)

1亿VIP精品文档

相关文档