其他分享
首页 > 其他分享> > leetcode学习笔记1010 Pairs of Songs With Total Durations Divisible by 60

leetcode学习笔记1010 Pairs of Songs With Total Durations Divisible by 60

作者:互联网

leetcode学习笔记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

0 和 30 单独计算, 其他的值直接去找对应的值是否存在就可以.

时间复杂度O(n).
空间复杂度O(1).

class Solution {
    
    public int numPairsDivisibleBy60(int[] time) {
        int[] count = new int[60];
        // 对60取余
        for(int t : time)
            count[t%60]++;
        
        int res = getPairCouns(count[0]) + getPairCouns(count[30]);
        
        for(int i = 1; i < 30; i++)
            res += count[i] * count[60 - i];
        
        return res;
    }
    
    private int getPairCouns(int n){
        return n*(n-1)/2;
    }
    
}

标签:count,Pairs,Divisible,60,int,time,duration,total
来源: https://blog.csdn.net/weixin_42498646/article/details/110912271