1010. Pairs of Songs With Total Durations Divisible by 60
You are given a list of songs where the ith song has a duration of time[i]
seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60
. Formally, we want the number of indices i
, j
such that i < j
with (time[i] + time[j]) % 60 == 0
.
Example 1:
Input: time = [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60
Example 2:
Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
Constraints:
1 <= time.length <= 6 * 104
1 <= time[i] <= 500
题目:在歌曲列表中,第 i
首歌曲的持续时间为 time[i]
秒。返回其总持续时间(以秒为单位)可被 60
整除的歌曲对的数量。形式上,我们希望索引的数字 i
和 j
满足 i < j
且有 (time[i] + time[j]) % 60 == 0
。
思路:参考lee215。首先将每个元素按60取余,那么题目转变为求满足Two Sum为60的元素对的数目。考虑当前元素 time[i]
,只需统计在当前元素之前满足 time[i] % 60 = 60 - (time[j] % 60)
,对应 j
( j < i
)的数目。对于边界,假设 time[i]=60
,那么我们希望 time[j]%60=0
,因此将要找的目标值 60 - (time[j] % 60)
转换为 (60 - (time[j] % 60)) % 60
。
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
vector<int> c(60);
int res = 0;
for(auto t : time){
res += c[(60 - t % 60) % 60];
c[t % 60] += 1;
}
return res;
}
};