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.

【数论】leetcode1010. Pairs of Songs With Total Durations Divisible by 60_i++

题意:2个数和是60的倍数。求答案的对数。

思路:

当两个数模60的余数互补时,两个数的和是60的倍数。模的情况只能是0~59.

所以可以开大小为60 的数组。

假设遍历到i,s[x]表示在前i-1出现模为x的次数。(根据对称性,所以只考虑前面的数,且不包括自己)

 

【数论】leetcode1010. Pairs of Songs With Total Durations Divisible by 60_算法_02

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int n=time.length;
        int[] s=new int[60];
        int res=0;
        for(int i=0;i<n;i++){
            res+=s[(60-time[i]%60)%60];
            s[time[i]%60]++;
        }
        return res;
        }
    
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.