KK's blog

每天积累多一些

0%

LeetCode 1010 Pairs of Songs With Total Durations Divisible by 60

LeetCode



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.

Example 1:

Input: time = [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: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.


Constraints:

`1 <= time.length <= 6 104*1 <= time[i] <= 500`

题目大意:

求数组中两数和能被60整除

解题思路:

两数和的关系第一时间想到two sum。但由于target是60的倍数,并不固定,所以先用公式求所有数的mod,(time[i] + time[j]) % 60 = time[i] % 60 + time[j] % 60, 这样target就是60了
第二个难点是此题求个数并不是像two sum一样求可行性,所以value to index改成value to count

解题步骤:

N/A

注意事项:

  1. 对所有数对60求mod,map存value到count
  2. 如果输入是60,取模后为0, 求(60 - time_mod[i])要对60取模,否则60不在map中,因为60 - time_mod[i] = 60.

Python代码:

1
2
3
4
5
6
7
8
9
10
# (time[i] + time[j]) % 60 = time[i] % 60 + time[j] % 60
def numPairsDivisibleBy60(self, time: List[int]) -> int:
time_mod = [t % 60 for t in time] # [30,30]
val_to_count = collections.defaultdict(int)
res = 0
for i in range(len(time_mod)):
if (60 - time_mod[i]) % 60 in val_to_count:
res += val_to_count[(60 - time_mod[i]) % 60]
val_to_count[time_mod[i]] += 1 # 30:1
return res

算法分析:

时间复杂度为O(n),空间复杂度O(n)

Free mock interview