leetcode 算法题1010 (简单266) 总持续时间可被 60 整除的歌曲
- 题目介绍
在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。
返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。
形式上,我们希望索引的数字 i < j 且有 (time[i] + time[j]) % 60 == 0。
- 示例
输入:[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
输入:[60,60,60]
输出:3
解释:所有三对的总持续时间都是 120,可以被 60 整数。
- 提示
1 <= time.length <= 60000
1 <= time[i] <= 500
- 解法一
/**
* @param {number[]} time
* @return {number}
*/
var numPairsDivisibleBy60 = function(time) {
let i = 0, count = 0;
while(i < time.length - 1) {
let j = i + 1;
while(j < time.length) {
if((time[i] + time[j++]) % 60 === 0) {
count++;
}
}
i++;
}
return count;
};
执行用时 : 6776 ms, 在所有 JavaScript 提交中击败了54.64%的用户
内存消耗 : 37.8 MB, 在所有 JavaScript 提交中击败了37.98%的用户
- 解法二
/**
* @param {number[]} time
* @return {number}
*/
var numPairsDivisibleBy60 = function(time) {
let i = 0, count = 0, counts = Array(60).fill(0);
while(i < time.length) {
count += counts[(60 - time[i] % 60) % 60];
counts[time[i++] % 60]++;
}
return count;
};
执行用时 : 72 ms, 在所有 JavaScript 提交中击败了100.00%的用户
内存消耗 : 37.3 MB, 在所有 JavaScript 提交中击败了84.81%的用户