LeetCode 题解工作台

总持续时间可被 60 整除的歌曲

在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。 返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 i 和 j 满足 i 且有 (time[i] + time[j]) % 60 == 0 。 示例 1: 输入: time = [30,20,150,…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数组·哈希·扫描

bolt

答案摘要

如果一个数对 $(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 AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。

返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 ij 满足  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 * 104
  • 1 <= time[i] <= 500
lightbulb

解题思路

方法一:数学 + 计数

如果一个数对 (a,b)(a, b) 之和能被 6060 整除,即 (a+b)mod60=0(a + b) \bmod 60 = 0,那么 (amod60+bmod60)mod60=0(a \bmod 60 + b \bmod 60) \bmod 60 = 0,不妨记 x=amod60x=a \bmod 60, y=bmod60y = b \bmod 60,那么有 (x+y)mod60=0(x + y) \bmod 60 = 0,即 y=(60x)mod60y=(60 - x) \bmod 60

因此,我们可以遍历歌曲列表,用一个长度为 6060 的数组 cntcnt 记录每个余数 xx 出现的次数。对于当前的 xx,如果数组 cntcnt 中存在余数 y=(60x)mod60y = (60 - x) \bmod 60,那么将 cnt[y]cnt[y] 累加进答案中。然后,将 xx 在数组 cntcnt 中的出现次数加 11。继续遍历,直到遍历完整个歌曲列表。

遍历结束后,即可得到满足条件的歌曲对数目。

时间复杂度 O(n)O(n),空间复杂度 O(C)O(C)。其中 nn 是歌曲列表的长度;而 CC 是余数的可能取值,这里 C=60C=60

1
2
3
4
5
6
7
8
9
10
11
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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

warning

常见陷阱

外企场景
  • 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

swap_horiz

进阶变体

外企场景
  • 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

help

常见问题

外企场景

总持续时间可被 60 整除的歌曲题解:数组·哈希·扫描 | LeetCode #1010 中等