- 0
- 0
- 约7.39千字
- 约 21页
- 2026-01-23 发布于福建
- 举报
第PAGE页共NUMPAGES页
2026年字节跳动招聘笔试技巧解析
一、编程基础(共5题,每题2分,总计10分)
考察内容:数据结构、算法基础、编程语言(以Java/Python为主)
1.题目:
给定一个无重复元素的整数数组`nums`,返回其所有可能的全排列。
示例:`nums=[1,2,3]`,返回`[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]`。
请用Python实现该功能,要求时间复杂度尽可能低。
答案:
python
defpermute(nums):
defbacktrack(first=0):
iffirst==n:
output.append(nums[:])
foriinrange(first,n):
nums[first],nums[i]=nums[i],nums[first]
backtrack(first+1)
nums[first],nums[i]=nums[i],nums[first]
n=len(nums)
output=[]
backtrack()
returnoutput
解析:
-使用回溯算法,通过交换元素生成所有排列。
-时间复杂度:O(n!),空间复杂度:O(n),适合小规模输入。
-字节跳动注重代码可读性和效率,需避免暴力枚举。
2.题目:
实现一个LRU(LeastRecentlyUsed)缓存,支持`get`和`put`操作。
要求:
-`get(key)`:返回键对应的值,若不存在返回-1。
-`put(key,value)`:插入或更新键值对,当缓存容量满时,删除最久未使用的键。
示例:
python
lru=LRUCache(2)
lru.put(1,1)
lru.put(2,2)
lru.get(1)#返回1
lru.put(3,3)#去除键2
lru.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=self.order.pop(0)
delself.cache[oldest]
self.cache[key]=value
self.order.append(key)
解析:
-使用哈希表(`cache`)存储键值对,列表(`order`)记录访问顺序。
-`get`操作需将键移至队尾表示最近使用。
-`put`操作需删除最久未使用的键(队首元素),若超出容量。
3.题目:
判断一个链表是否为回文链表。
示例:
python
head=[1,2,2,1]
输出:true
head=[1,2]
输出:false
答案:
python
defisPalindrome(head:ListNode)-bool:
ifnotheadornothead.next:
returnTrue
slow=fast=head
whilefastandfast.next:
slow=slow.next
fast=fast.next.next
反转后半部分
prev=None
whileslow:
temp=slow.next
slow.next=prev
prev=slow
slow=temp
对比前后半部分
left,right=head,prev
whileright:#只需比较到中间即可
ifleft.val!=right.val:
returnFalse
left=left.next
right=right.next
returnTrue
解析:
-快慢指针定位中点,反转后半部分,逐个比较。
-时间复杂度:O(n),空间复杂度:O(1),适
原创力文档

文档评论(0)