题目

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:

  1. Input: time = [30,20,150,100,40]
  2. Output: 3
  3. Explanation: Three pairs have a total duration divisible by 60:
  4. (time[0] = 30, time[2] = 150): total duration 180
  5. (time[1] = 20, time[3] = 100): total duration 120
  6. (time[1] = 20, time[4] = 40): total duration 60

Example 2:

  1. Input: time = [60,60,60]
  2. Output: 3
  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

  1. class Solution {
  2. public int numPairsDivisibleBy60(int[] time) {
  3. int count = 0;
  4. int[] remainders = new int[60];
  5. for (int num : time) {
  6. int remainder = num % 60;
  7. if (remainder == 0) {
  8. count += remainders[0];
  9. } else {
  10. count += remainders[60 - remainder];
  11. }
  12. remainders[remainder]++;
  13. }
  14. return count;
  15. }
  16. }