LeetCode 题解工作台
总持续时间可被 60 整除的歌曲
在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。 返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 i 和 j 满足 i 且有 (time[i] + time[j]) % 60 == 0 。 示例 1: 输入: time = [30,20,150,…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
如果一个数对 $(a, b)$ 之和能被 整除,即 $(a + b) \bmod 60 = 0$,那么 $(a \bmod 60 + b \bmod 60) \bmod 60 = 0$,不妨记 $x=a \bmod 60$, $y = b \bmod 60$,那么有 $(x + y) \bmod 60 = 0$,即 $y=(60 - x) \bmod 60$。 因此,我们可以遍历歌曲列表,用一个…
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 i 和 j 满足 i < j 且有 (time[i] + time[j]) % 60 == 0。
示例 1:
输入:time = [30,20,150,100,40] 输出:3 解释:这三对的总持续时间可被 60 整除: (time[0] = 30, time[2] = 150): 总持续时间 180 (time[1] = 20, time[3] = 100): 总持续时间 120 (time[1] = 20, time[4] = 40): 总持续时间 60
示例 2:
输入:time = [60,60,60] 输出:3 解释:所有三对的总持续时间都是 120,可以被 60 整除。
提示:
1 <= time.length <= 6 * 1041 <= time[i] <= 500
解题思路
方法一:数学 + 计数
如果一个数对 之和能被 整除,即 ,那么 ,不妨记 , ,那么有 ,即 。
因此,我们可以遍历歌曲列表,用一个长度为 的数组 记录每个余数 出现的次数。对于当前的 ,如果数组 中存在余数 ,那么将 累加进答案中。然后,将 在数组 中的出现次数加 。继续遍历,直到遍历完整个歌曲列表。
遍历结束后,即可得到满足条件的歌曲对数目。
时间复杂度 ,空间复杂度 。其中 是歌曲列表的长度;而 是余数的可能取值,这里 。
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
cnt = Counter()
ans = 0
for x in time:
x %= 60
y = (60 - x) % 60
ans += cnt[y]
cnt[x] += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) for scanning the array once. Space complexity is O(60) = O(1) due to storing counts for each possible remainder modulo 60. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for a hash map or remainder counting solution
- question_mark
Mentions modulo arithmetic or pair summing
- question_mark
Checks for handling edge cases with zero or multiple of 60 durations
常见陷阱
外企场景- error
Double-counting pairs when scanning array
- error
Ignoring songs with remainder 0 or 30 specially
- error
Using nested loops leading to O(n^2) time instead of hash approach
进阶变体
外企场景- arrow_right_alt
Count pairs divisible by k instead of 60
- arrow_right_alt
Return the actual index pairs rather than the count
- arrow_right_alt
Handle streaming input of song durations