返回
LeetCode 2274. 无特殊楼层的最大连续楼层(python)
后端
2023-12-01 15:35:13
题意理解:
- 给定一个整数数组 special 表示有特殊房间的楼层
- 给定整数 numSpecial 表示有特殊房间的楼层数
- 找到一个连续的楼层范围,使得该范围内的楼层没有特殊房间
- 返回这个范围的楼层数,即为无特殊楼层的最大连续楼层
python 解答:
def maxConsecutive(special: list[int], numSpecial: int) -> int:
"""
:type special: List[int]
:type numSpecial: int
:rtype: int
"""
# 对特殊楼层进行排序
special.sort()
# 初始化最大连续楼层数和当前连续楼层数
max_consecutive = 0
current_consecutive = 0
# 遍历特殊楼层数组
for i in range(len(special)):
# 如果当前楼层和上一个楼层相差大于 1,则更新最大连续楼层数
if i > 0 and special[i] - special[i - 1] > 1:
max_consecutive = max(max_consecutive, current_consecutive)
current_consecutive = 0
# 更新当前连续楼层数
current_consecutive += 1
# 处理最后一个特殊楼层后的连续楼层数
max_consecutive = max(max_consecutive, current_consecutive)
# 返回最大连续楼层数
return max_consecutive
时间复杂度分析:
由于我们对特殊楼层数组进行了排序,因此时间复杂度为 O(nlogn),其中 n 为特殊楼层数组的长度。
空间复杂度分析:
空间复杂度为 O(1),因为我们没有使用额外的空间。
示例:
>>> special = [1, 3, 7, 9, 11, 17, 19, 23, 29, 31]
>>> numSpecial = 4
>>> maxConsecutive(special, numSpecial)
5