描述
在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字 i 和 j 满足 i < j 且有 (time[i] + time[j]) % 60 == 0。
示例 1:
输入:[30,20,150,100,40]
输出:3
解释:这三对的总持续时间可被 60 整数:
(time[0] = 30, time[2] = 150): 总持续时间 180
(time[1] = 20, time[3] = 100): 总持续时间 120
(time[1] = 20, time[4] = 40): 总持续时间 60
示例 2:
输入:[60,60,60]
输出:3
解释:所有三对的总持续时间都是 120,可以被 60 整数。
AC代码
//一年多没搞算法了,丑的自己都看不下去
class Solution {
public int numPairsDivisibleBy60(int[] time) {
int count = 0;
int mqs[] =new int[60];
Arrays.fill(mqs,0);
for(int i =0; i<time.length; i++){
mqs[time[i] % 60] ++;
}
for (int i = 1; i<30; i++){
count = count + mqs[i] * mqs[60-i];
}
for (int i=1; i<mqs[0]; i++){
count += i;
}
for (int i=1; i<mqs[30]; i++){
count += i;
}
return count;
}
}
//最美的代码
class Solution {
public int numPairsDivisibleBy60(int[] time) {
int[] record = new int[60];
int count = 0;
for(int t : time){
t %= 60; //求这个时间的余数
if(t != 0)
count += record[60 - t]; //如果时间余数不为0,找出相加为0的余数总和相加
else count += record[t]; //如果为0,加其他为0的数
record[t] ++;
}
return count;
}
}
反思:先不说代码的简洁程度,这个思考的角度就比我好了太多。我只想到了遍历取模后两两比对,他在遍历时就进行了操作,无需二次调用。需要重新学习的地方有太多,开始脚踏实地。