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

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

在歌曲列表中,第 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 * 10^4
  • 1 <= time[i] <= 500

提示 1

We only need to consider each song length modulo 60.


提示 2

We can count the number of songs with (length % 60) equal to r, and store that in an array of size 60.

解法1:哈希表

同类题型:LeetCode 1. 两数之和-CSDN博客

LeetCode 1679. K 和数对的最大数目-CSDN博客

Java版:

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int ans = 0;
        Map<Integer, Integer> map = new HashMap<>();
        for (int t: time) {
            t %= 60;
            int k = (60 - t) % 60;
            if (map.containsKey(k)) {
                ans += map.get(k);
            }
            map.merge(t, 1, Integer::sum);
        }
        return ans;
    }
}

 

Python3版:

class Solution:
    def numPairsDivisibleBy60(self, time: List[int]) -> int:
        ans = 0
        dic = {}
        for t in time:
            t %= 60
            k = (60 - t) % 60
            if k in dic:
                ans += dic[k]
            dic[t] = dic[t] + 1 if t in dic else 1 
        return ans

复杂度分析

  • 时间复杂度:O(n),其中 n 为数组 time 的长度。
  • 空间复杂度:O(n),其中 n 为数组 time 的长度,主要为存储哈希表的空间开销。

解法2:数组

Java版:

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int ans = 0;
        int[] count = new int[60];
        for (int t: time) {
            t %= 60;
            int k = (60 - t) % 60;
            ans += count[k];
            count[t]++;
        }
        return ans;
    }
}

python3版:

class Solution:
    def numPairsDivisibleBy60(self, time: List[int]) -> int:
        ans = 0
        count = [0] * 60
        for t in time:
            t %= 60
            k = (60 - t) % 60
            ans += count[k]
            count[t] += 1
        return ans

复杂度分析

  • 时间复杂度:O(n),其中 n 为数组 time 的长度。
  • 空间复杂度:O(1),需要长度为 60 的数组。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值