Python 中总时长能被 60 整除的歌曲对
pythonserver side programmingprogramming更新于 2025/11/2 8:44:17
假设我们有一个歌曲列表,第 i 首歌曲的时长为 time[i] 秒。我们必须找出总时长(以秒为单位)能被 60 整除的歌曲对的数量。
因此,如果时间数组为 [30, 20, 150, 100, 40],则答案为 3。在所有总时长能被 60 整除的情况下,三对歌曲对分别为 (3, 150)、(20, 100)、(20, 40)。
为了解决这个问题,我们将遵循以下步骤 −
- 使用 map rem 来存储余数。设置 ans := 0
- 对于时间 − 中的所有元素 i
- 如果 i 可以被 0 整除且 rem 为 0,则 ans := ans + rem[0]
- o 否则当 rem 为 60 – (i mod 60) 时,则 ans := ans + rem[60 – (i mod 60)]
- 如果 rem 为 i mod 60,则 rem[i mod 60] := rem[i mod 60] + 1
- 否则 rem[i mod 60] := 1
- 返回 ans
示例
让我们看看下面的实现以便更好地理解 −
class Solution(object):
def numPairsDivisibleBy60(self, time):
ans = 0
remainder = {}
for i in time:
if i % 60 == 0 and 0 in remainder:
ans += remainder[0]
elif 60 - (i%60) in remainder:
ans += remainder[60 - (i%60)]
if i % 60 in remainder:
remainder[i%60]+=1
else:
remainder[i%60]=1
return ans
ob1 = Solution()
print(ob1.numPairsDivisibleBy60([30,20,150,100,40]))
输入
[30,20,150,100,40]
输出
3
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

