LeetCode 题解工作台

不含特殊楼层的最大连续楼层数

Alice 管理着一家公司,并租用大楼的部分楼层作为办公空间。Alice 决定将一些楼层作为 特殊楼层 ,仅用于放松。 给你两个整数 bottom 和 top ,表示 Alice 租用了从 bottom 到 top (含 bottom 和 top 在内)的所有楼层。另给你一个整数数组 special…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·排序

bolt

答案摘要

我们可以将特殊楼层按照升序排序,然后计算相邻两个特殊楼层之间的楼层数,最后再计算第一个特殊楼层和 之间的楼层数,以及最后一个特殊楼层和 之间的楼层数,取这些楼层数的最大值即可。 时间复杂度 $O(n \times \log n)$,空间复杂度 $O(\log n)$。其中 是数组 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

Alice 管理着一家公司,并租用大楼的部分楼层作为办公空间。Alice 决定将一些楼层作为 特殊楼层 ,仅用于放松。

给你两个整数 bottomtop ,表示 Alice 租用了从 bottomtop(含 bottomtop 在内)的所有楼层。另给你一个整数数组 special ,其中 special[i] 表示  Alice 指定用于放松的特殊楼层。

返回不含特殊楼层的 最大 连续楼层数。

 

示例 1:

输入:bottom = 2, top = 9, special = [4,6]
输出:3
解释:下面列出的是不含特殊楼层的连续楼层范围:
- (2, 3) ,楼层数为 2 。
- (5, 5) ,楼层数为 1 。
- (7, 9) ,楼层数为 3 。
因此,返回最大连续楼层数 3 。

示例 2:

输入:bottom = 6, top = 8, special = [7,6,8]
输出:0
解释:每层楼都被规划为特殊楼层,所以返回 0 。

 

提示

  • 1 <= special.length <= 105
  • 1 <= bottom <= special[i] <= top <= 109
  • special 中的所有值 互不相同
lightbulb

解题思路

方法一:排序

我们可以将特殊楼层按照升序排序,然后计算相邻两个特殊楼层之间的楼层数,最后再计算第一个特殊楼层和 bottom\textit{bottom} 之间的楼层数,以及最后一个特殊楼层和 top\textit{top} 之间的楼层数,取这些楼层数的最大值即可。

时间复杂度 O(n×logn)O(n \times \log n),空间复杂度 O(logn)O(\log n)。其中 nn 是数组 special\textit{special} 的长度。

1
2
3
4
5
6
7
8
class Solution:
    def maxConsecutive(self, bottom: int, top: int, special: List[int]) -> int:
        special.sort()
        ans = max(special[0] - bottom, top - special[-1])
        for x, y in pairwise(special):
            ans = max(ans, y - x - 1)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Sorting special floors is critical for correct gap calculation.

  • question_mark

    Checking all edge cases including first and last floor gaps is expected.

  • question_mark

    Tracking maximum while iterating shows understanding of array manipulation patterns.

warning

常见陷阱

外企场景
  • error

    Forgetting to sort special floors before computing gaps leads to incorrect results.

  • error

    Ignoring the gap before the first special floor or after the last special floor can miss the true maximum.

  • error

    Assuming consecutive floors are only between special floors and not including bottom and top boundaries.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return both the maximum consecutive floors and the starting floor of that sequence.

  • arrow_right_alt

    Count the total number of consecutive sequences longer than a given threshold.

  • arrow_right_alt

    Allow dynamic insertion of special floors and compute the maximum consecutive floors after each insertion.

help

常见问题

外企场景

不含特殊楼层的最大连续楼层数题解:数组·排序 | LeetCode #2274 中等