leetcode

package
v0.0.0-...-3200de1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2023 License: MIT Imports: 0 Imported by: 0

README

1010. Pairs of Songs With Total Durations Divisible by 60

题目

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 ij 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

题目大意

在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。

返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望下标数字 i 和 j 满足  i < j 且有 (time[i] + time[j]) % 60 == 0。

解题思路

  • 简单题。先将数组每个元素对 60 取余,将它们都转换到 [0,59] 之间。然后在数组中找两两元素之和等于 60 的数对。可以在 0-30 之内对半查找符合条件的数对。对 0 和 30 单独计算。因为多个 0 相加,余数还为 0 。2 个 30 相加之和为 60。

代码

func numPairsDivisibleBy60(time []int) int {
	counts := make([]int, 60)
	for _, v := range time {
		v %= 60
		counts[v]++
	}
	res := 0
	for i := 1; i < len(counts)/2; i++ {
		res += counts[i] * counts[60-i]
	}
	res += (counts[0] * (counts[0] - 1)) / 2
	res += (counts[30] * (counts[30] - 1)) / 2
	return res
}

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL