LeetCode 题解工作台

构成整天的下标对数目 I

给你一个整数数组 hours ,表示以 小时 为单位的时间,返回一个整数,表示满足 i 且 hours[i] + hours[j] 构成 整天 的下标对 i , j 的数目。 整天 定义为时间持续时间是 24 小时的 整数倍 。 例如,1 天是 24 小时,2 天是 48 小时,3 天是 72 小时…

category

3

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们可以用一个哈希表或者一个长度为 的数组 来记录每个小时数模 的出现次数。 遍历数组 ,对于每个小时数 ,我们可以得出与 相加为 的倍数,且模 之后的数为 $(24 - x \bmod 24) \bmod 24$。累加这个数在哈希表或者数组中的出现次数即可。然后我们将 的模 的出现次数加一。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 hours,表示以 小时 为单位的时间,返回一个整数,表示满足 i < jhours[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 <= 100
  • 1 <= hours[i] <= 109
lightbulb

解题思路

方法一:计数

我们可以用一个哈希表或者一个长度为 2424 的数组 cnt\textit{cnt} 来记录每个小时数模 2424 的出现次数。

遍历数组 hours\textit{hours},对于每个小时数 xx,我们可以得出与 xx 相加为 2424 的倍数,且模 2424 之后的数为 (24xmod24)mod24(24 - x \bmod 24) \bmod 24。累加这个数在哈希表或者数组中的出现次数即可。然后我们将 xx 的模 2424 的出现次数加一。

遍历完数组 hours\textit{hours} 后,我们就可以得到满足题意的下标对数目。

时间复杂度 O(n)O(n),其中 nn 为数组 hours\textit{hours} 的长度。空间复杂度 O(C)O(C),其中 C=24C=24

1
2
3
4
5
6
7
8
9
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
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

构成整天的下标对数目 I题解:数组·哈希·扫描 | LeetCode #3184 简单