LeetCode 题解工作台
按下时间最长的按钮
给你一个二维数组 events ,表示孩子在键盘上按下一系列按钮触发的按钮事件。 每个 events[i] = [index i , time i ] 表示在时间 time i 时,按下了下标为 index i 的按钮。 数组按照 time 的递增顺序 排序 。 按下一个按钮所需的时间是连续两次按钮…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·driven
答案摘要
我们定义两个变量 和 ,分别表示按下时间最长的按钮的索引和按下时间。 接下来,我们从下标 $k = 1$ 开始遍历数组 ,对于每个 ,我们计算当前按钮的按下时间 $d = t2 - t1$,其中 是当前按钮的按下时间,而 是前一个按钮的按下时间。如果 $d > t$ 或者 $d = t$ 且当前按钮的索引 小于 ,我们更新 $\textit{ans} = i$ 和 $t = d$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·driven 题型思路
题目描述
给你一个二维数组 events,表示孩子在键盘上按下一系列按钮触发的按钮事件。
每个 events[i] = [indexi, timei] 表示在时间 timei 时,按下了下标为 indexi 的按钮。
- 数组按照
time的递增顺序排序。 - 按下一个按钮所需的时间是连续两次按钮按下的时间差。按下第一个按钮所需的时间就是其时间戳。
返回按下时间 最长 的按钮的 index。如果有多个按钮的按下时间相同,则返回 index 最小的按钮。
示例 1:
输入: events = [[1,2],[2,5],[3,9],[1,15]]
输出: 1
解释:
- 下标为 1 的按钮在时间 2 被按下。
- 下标为 2 的按钮在时间 5 被按下,因此按下时间为
5 - 2 = 3。 - 下标为 3 的按钮在时间 9 被按下,因此按下时间为
9 - 5 = 4。 - 下标为 1 的按钮再次在时间 15 被按下,因此按下时间为
15 - 9 = 6。
最终,下标为 1 的按钮按下时间最长,为 6。
示例 2:
输入: events = [[10,5],[1,7]]
输出: 10
解释:
- 下标为 10 的按钮在时间 5 被按下。
- 下标为 1 的按钮在时间 7 被按下,因此按下时间为
7 - 5 = 2。
最终,下标为 10 的按钮按下时间最长,为 5。
提示:
1 <= events.length <= 1000events[i] == [indexi, timei]1 <= indexi, timei <= 105- 输入保证数组
events按照timei的递增顺序排序。
解题思路
方法一:一次遍历
我们定义两个变量 和 ,分别表示按下时间最长的按钮的索引和按下时间。
接下来,我们从下标 开始遍历数组 ,对于每个 ,我们计算当前按钮的按下时间 ,其中 是当前按钮的按下时间,而 是前一个按钮的按下时间。如果 或者 且当前按钮的索引 小于 ,我们更新 和 。
最后,我们返回 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def buttonWithLongestTime(self, events: List[List[int]]) -> int:
ans, t = events[0]
for (_, t1), (i, t2) in pairwise(events):
d = t2 - t1
if d > t or (d == t and i < ans):
ans, t = i, d
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each event is processed once. Space complexity is O(1) since only a few variables are needed for maximum tracking, regardless of input size. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate starts by calculating durations correctly from the events array.
- question_mark
Candidate correctly handles ties by comparing indices.
- question_mark
Candidate uses minimal space and a single-pass iteration showing array pattern understanding.
常见陷阱
外企场景- error
Forgetting to compute duration using the previous event's time, not the first event only.
- error
Not handling multiple buttons with equal maximum duration, ignoring smallest index rule.
- error
Attempting to store all durations instead of tracking the maximum in a single pass, wasting space.
进阶变体
外企场景- arrow_right_alt
Input arrays with large numbers to test integer handling and duration calculation.
- arrow_right_alt
Events where the first and last buttons tie for maximum duration.
- arrow_right_alt
Sparse events with non-consecutive button indices to ensure array iteration logic is robust.