- 1
- 0
- 约3.81千字
- 约 10页
- 2026-01-17 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年IT算法工程师面试题及答案
一、编程实现题(共3题,每题20分,合计60分)
题目1(20分):
实现一个无重复字符的最长子串查找函数,输入一个字符串`s`,返回最长子串的长度。要求时间复杂度不超过O(n),空间复杂度不超过O(1)。
例如:输入`s=abcabcbb`,输出`3`(最长子串为abc)。
答案:
python
deflength_of_longest_substring(s:str)-int:
char_set=set()
left=0
max_len=0
forrightinrange(len(s)):
whiles[right]inchar_set:
char_set.remove(s[left])
left+=1
char_set.add(s[right])
max_len=max(max_len,right-left+1)
returnmax_len
解析:
使用滑动窗口方法,`left`和`right`分别表示窗口的左右边界。遍历字符串时,如果当前字符`right`已在窗口中,则移动`left`直到移除重复字符。时间复杂度为O(n),空间复杂度为O(1)(假设字符集大小固定)。
题目2(20分):
给定一个包含`n`个整数的数组`nums`和一个目标值`target`,找出数组中和为目标值的三元组个数。要求时间复杂度不超过O(n^2)。
例如:输入`nums=[-1,0,1,2,-1,-4]`,`target=0`,输出`2`(三元组为[-1,0,1]和[-1,-1,2])。
答案:
python
defthree_sum(nums:list)-int:
nums.sort()
n=len(nums)
count=0
foriinrange(n):
ifi0andnums[i]==nums[i-1]:
continue
left,right=i+1,n-1
whileleftright:
total=nums[i]+nums[left]+nums[right]
iftotal==0:
count+=1
left_val=nums[left]
right_val=nums[right]
whileleftrightandnums[left]==left_val:
left+=1
whileleftrightandnums[right]==right_val:
right-=1
eliftotal0:
left+=1
else:
right-=1
returncount
解析:
先对数组排序,然后固定第一个数,使用双指针遍历剩余部分。为避免重复计算,跳过重复的数。时间复杂度为O(n^2),空间复杂度为O(1)。
题目3(20分):
实现一个LRU(最近最少使用)缓存,支持`get`和`put`操作。要求`get`操作时间复杂度为O(1),`put`操作时间复杂度为O(1)。
例如:
初始化LRU缓存容量为2。
`put(1,1)`:缓存是{1:1}。
`put(2,2)`:缓存是{1:1,2:2}。
`get(1)`:返回1。
`put(3,3)`:缓存是{2:2,3:3}(删除1)。
`get(2)`:返回2。
答案:
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=self.order.pop(0)
delself.cache[oldest]
self.cache[key]=value
self.order.append(key)
解析:
使用哈希表存储键值对,双端队列维护访问顺序。`get`时将键移到队尾,`put`时先删除最久未
原创力文档

文档评论(0)