1010. Pairs of Songs With Total Durations Divisible by 60 (M)

Pairs of Songs With Total Durations Divisible by 60 (M)

题目

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

题意

在数组中找一对数,使它们的和能被60整除,求这样的数对的个数。

思路

Hash。遍历数组,计算当前数除以60的余数R,如果R为0,在结果上加上之前余数为0的数的个数;如果R不为0,在结果上加上之前余数为60-R的数的个数。


代码实现

Java

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int count = 0;
        int[] remainders = new int[60];

        for (int num : time) {
            int remainder = num % 60;
            if (remainder == 0) {
                count += remainders[0];
            } else {
                count += remainders[60 - remainder];
            }
            remainders[remainder]++;
        }

        return count;
    }
}
posted @ 2020-12-08 17:49  墨云黑  阅读(153)  评论(0编辑  收藏  举报