Pairs of Songs With Total Durations Divisible by 60

In a list of songs, the i-th 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 with (time[i] + time[j]) % 60 == 0.

 

Example 1:

Input: [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: [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.

 

Note:

  1. 1 <= time.length <= 60000
  2. 1 <= time[i] <= 500

 

题目理解:

给定一个数组,找出其中所有的合法对,每一个合法对相加是60的倍数

解题思路:

将所有的数字根据其模60的余数,分为60组,然后分别组合,例如余数为1的组中的数字与余数是59的组中的数字组合。对于余数是0的组,和余数是30的组,从组内部随机选两个就可以了

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int res = 0;
        int len = time.length;
        int[] record = new int[60];
        for(int num : time)
            record[num % 60]++;
        res += record[0] * (record[0] - 1) / 2;
        res += record[30] * (record[30] - 1) / 2;
        int left = 1, right = 59;
        while(left < right){
            res += record[left] * record[right];
            left++;
            right--;
        }
        return res;
    }
}

 

你可能感兴趣的:(LeetCode)