LeetCode 题解工作台
构成整天的下标对数目 I
给你一个整数数组 hours ,表示以 小时 为单位的时间,返回一个整数,表示满足 i 且 hours[i] + hours[j] 构成 整天 的下标对 i , j 的数目。 整天 定义为时间持续时间是 24 小时的 整数倍 。 例如,1 天是 24 小时,2 天是 48 小时,3 天是 72 小时…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们可以用一个哈希表或者一个长度为 的数组 来记录每个小时数模 的出现次数。 遍历数组 ,对于每个小时数 ,我们可以得出与 相加为 的倍数,且模 之后的数为 $(24 - x \bmod 24) \bmod 24$。累加这个数在哈希表或者数组中的出现次数即可。然后我们将 的模 的出现次数加一。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你一个整数数组 hours,表示以 小时 为单位的时间,返回一个整数,表示满足 i < j 且 hours[i] + hours[j] 构成 整天 的下标对 i, j 的数目。
整天 定义为时间持续时间是 24 小时的 整数倍 。
例如,1 天是 24 小时,2 天是 48 小时,3 天是 72 小时,以此类推。
示例 1:
输入: hours = [12,12,30,24,24]
输出: 2
解释:
构成整天的下标对分别是 (0, 1) 和 (3, 4)。
示例 2:
输入: hours = [72,48,24,3]
输出: 3
解释:
构成整天的下标对分别是 (0, 1)、(0, 2) 和 (1, 2)。
提示:
1 <= hours.length <= 1001 <= hours[i] <= 109
解题思路
方法一:计数
我们可以用一个哈希表或者一个长度为 的数组 来记录每个小时数模 的出现次数。
遍历数组 ,对于每个小时数 ,我们可以得出与 相加为 的倍数,且模 之后的数为 。累加这个数在哈希表或者数组中的出现次数即可。然后我们将 的模 的出现次数加一。
遍历完数组 后,我们就可以得到满足题意的下标对数目。
时间复杂度 ,其中 为数组 的长度。空间复杂度 ,其中 。
class Solution:
def countCompleteDayPairs(self, hours: List[int]) -> int:
cnt = Counter()
ans = 0
for x in hours:
ans += cnt[(24 - (x % 24)) % 24]
cnt[x % 24] += 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) due to a single pass over the array with constant-time hash operations. Space complexity is O(24) = O(1) for the remainder hash map since there are only 24 possible remainders. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks about handling large numbers or values exceeding 24 hours.
- question_mark
Checks if you can optimize from brute force to a hash-based approach.
- question_mark
Wants clarity on handling modulo arithmetic and avoiding double counting.
常见陷阱
外企场景- error
Brute force all pairs instead of using modulo hash counting.
- error
Forgetting to handle the remainder 0 correctly, which forms complete days with itself.
- error
Double counting pairs by not ensuring i < j.
进阶变体
外企场景- arrow_right_alt
Count pairs that sum to a multiple of k instead of 24, changing the modulo base.
- arrow_right_alt
Return the list of pairs themselves instead of just the count, requiring more storage.
- arrow_right_alt
Handle negative or zero hours while still using the modulo hash approach.