LeetCode-1010

力扣1010题

题目描述:总持续时间可被60整除的歌曲

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

返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 i 和 j 满足 i < j 且有 (time[i] + time[j]) % 60 == 0。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/pairs-of-songs-with-total-durations-divisible-by-60
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

image.png

题解思路:

很容易想到的就是双指针遍历,但是会超时,时间复杂度不行,因此需要换种思路。

① 新建一个长度为60的数组,用来存放每个元素的余数的个数

② 遍历time[],先加到ans中,再更新,避免重复。

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int ans = 0;
        int[] res = new int[60];
        for(int t : time){
            ans += res[(60-t%60)%60];//判断是否存在(60-t)%60,有+1,没有就是0
            res[t % 60]++;
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/Miss_croal/article/details/130539091