余数为 i, i\in[1,29] 的歌曲。他们需要与余数为 60-i 的歌曲组成对。歌曲对的数量为 \sum_{i=1}^{29}\textit{cnt}[i] \times \textit{cnt}[60-i]。
余数为 i, i\in[31,59] 的歌曲。已经在上一部分组对过,不需要重复计算。
把这几部分求和,就可以得到最后的对数。
代码
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10
classSolution: defnumPairsDivisibleBy60(self, time: List[int]) -> int: cnt = [0] * 60 for t in time: cnt[t % 60] += 1 res = 0 for i inrange(1, 30): res += cnt[i] * cnt[60 - i] res += cnt[0] * (cnt[0] - 1) // 2 + cnt[30] * (cnt[30] - 1) // 2 return res
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publicintnumPairsDivisibleBy60(int[] time) { int[] cnt = newint[60]; for (int t : time) { cnt[t % 60]++; } longres=0; for (inti=1; i < 30; i++) { res += cnt[i] * cnt[60 - i]; } res += (long) cnt[0] * (cnt[0] - 1) / 2 + (long) cnt[30] * (cnt[30] - 1) / 2; return (int) res; } }
[sol1-C#]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicclassSolution { publicintNumPairsDivisibleBy60(int[] time) { int[] cnt = newint[60]; foreach (int t in time) { cnt[t % 60]++; } long res = 0; for (int i = 1; i < 30; i++) { res += cnt[i] * cnt[60 - i]; } res += (long) cnt[0] * (cnt[0] - 1) / 2 + (long) cnt[30] * (cnt[30] - 1) / 2; return (int) res; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: intnumPairsDivisibleBy60(vector<int>& time){ vector<int> cnt(60); for (int t : time) { cnt[t % 60]++; } longlong res = 0; for (int i = 1; i < 30; i++) { res += cnt[i] * cnt[60 - i]; } res += (longlong)cnt[0] * (cnt[0] - 1) / 2 + (longlong)cnt[30] * (cnt[30] - 1) / 2; return (int)res; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12
funcnumPairsDivisibleBy60(time []int)int { cnt := make([]int, 60) for _, t := range time { cnt[t % 60]++ } var res int for i := 1; i < 30; i++ { res += cnt[i] * cnt[60 - i] } res += cnt[0] * (cnt[0] - 1) / 2 + cnt[30] * (cnt[30] - 1) / 2 return res }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12
var numPairsDivisibleBy60 = function(time) { const cnt = newArray(60).fill(0); for (let t of time) { cnt[t % 60]++; } let res = 0; for (let i = 1; i < 30; i++) { res += cnt[i] * cnt[60 - i]; } res += cnt[0] * (cnt[0] - 1) / 2 + cnt[30] * (cnt[30] - 1) / 2; return res; }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13
intnumPairsDivisibleBy60(int* time, int timeSize) { int cnt[60]; memset(cnt, 0, sizeof(cnt)); for (int i = 0; i < timeSize; i++) { cnt[time[i] % 60]++; } longlong res = 0; for (int i = 1; i < 30; i++) { res += cnt[i] * cnt[60 - i]; } res += (longlong)cnt[0] * (cnt[0] - 1) / 2 + (longlong)cnt[30] * (cnt[30] - 1) / 2; return (int)res; }