程序员代码面试

[LeetCode] Pairs of Songs With T

2019-04-21  本文已影响0人  埋没随百草

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 <= time.length <= 60000
1 <= time[i] <= 500

解题思路

最简单的思路是使用两个for循环,判断加起来是否是60的倍数,然后果断超时了。

改进后的思路是:使用一个数组来存储余数(t % 60)的个数,然后每个元素可以组成的pair数目就是数组中位置为(60 - t % 60) % 60的元素的大小。

要满足条件:(a + b) % 60 == 0,那么对于大多数例子是:
a % 60 + b % 60 == 60,同时也需要注意一个特殊的例子:a % 60 == 0 && b % 60 == 0;

实现代码

// Runtime: 3 ms, faster than 84.18% of Java online submissions for Pairs of Songs With Total Durations Divisible by 60.
// Memory Usage: 42.4 MB, less than 100.00% of Java online submissions for Pairs of Songs With Total Durations Divisible by 60.
class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        if (time.length < 2) {
            return 0;
        }
        
        int[] cnt = new int[60];
        int result = 0;
        for (int t : time) {
            result += cnt[(60 - t % 60) % 60];
            cnt[t % 60] += 1;
        }
        return result;
    }
}
上一篇下一篇

猜你喜欢

热点阅读