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

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 整除的歌曲对的数量。形式上,我们希望索引的数字 ij 满足 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值