LeetCode 题解工作台
优质数对的总数 II
给你两个整数数组 nums1 和 nums2 ,长度分别为 n 和 m 。同时给你一个 正整数 k 。 如果 nums1[i] 可以被 nums2[j] * k 整除,则称数对 (i, j) 为 优质数对 ( 0 , 0 )。 返回 优质数对 的总数。 示例 1: 输入: nums1 = [1,3,…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·哈希·扫描
答案摘要
我们用一个哈希表 记录数组 中每个数除以 的商的出现次数,用一个哈希表 记录数组 中每个数的出现次数。 接下来,我们枚举数组 中的每个数 ,对于每个数 ,我们枚举 的倍数 ,其中 的范围是 $[x, \textit{mx}]$,其中 是 中的最大键值,然后我们统计 的和,记为 ,最后我们将 $s \times v$ 累加到答案中,其中 是 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·哈希·扫描 题型思路
题目描述
给你两个整数数组 nums1 和 nums2,长度分别为 n 和 m。同时给你一个正整数 k。
如果 nums1[i] 可以被 nums2[j] * k 整除,则称数对 (i, j) 为 优质数对(0 <= i <= n - 1, 0 <= j <= m - 1)。
返回 优质数对 的总数。
示例 1:
输入:nums1 = [1,3,4], nums2 = [1,3,4], k = 1
输出:5
解释:
5个优质数对分别是 (0, 0), (1, 0), (1, 1), (2, 0), 和 (2, 2)。
示例 2:
输入:nums1 = [1,2,4,12], nums2 = [2,4], k = 3
输出:2
解释:
2个优质数对分别是 (3, 0) 和 (3, 1)。
提示:
1 <= n, m <= 1051 <= nums1[i], nums2[j] <= 1061 <= k <= 103
解题思路
方法一:哈希表 + 枚举倍数
我们用一个哈希表 记录数组 中每个数除以 的商的出现次数,用一个哈希表 记录数组 中每个数的出现次数。
接下来,我们枚举数组 中的每个数 ,对于每个数 ,我们枚举 的倍数 ,其中 的范围是 ,其中 是 中的最大键值,然后我们统计 的和,记为 ,最后我们将 累加到答案中,其中 是 。
时间复杂度 ,空间复杂度 ,其中 和 分别是数组 和 的长度,而 是数组 中的最大值。
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
cnt1 = Counter(x // k for x in nums1 if x % k == 0)
if not cnt1:
return 0
cnt2 = Counter(nums2)
ans = 0
mx = max(cnt1)
for x, v in cnt2.items():
s = sum(cnt1[y] for y in range(x, mx + 1, x))
ans += s * v
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + m) if using a hash map for counts and scanning each array once. Space complexity is O(m) for storing frequency counts of nums2 divided by k. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect candidate to identify divisible pairs using a combination of iteration and hash lookup.
- question_mark
Watch if candidate considers integer division carefully to avoid miscounting.
- question_mark
Check whether the solution handles arrays of size up to 10^5 efficiently without nested loops.
常见陷阱
外企场景- error
Attempting nested loops over nums1 and nums2 directly can cause timeouts on large inputs.
- error
Using floating point division instead of integer division may result in wrong pair counts.
- error
Failing to multiply nums2 elements by k before checking divisibility leads to incorrect results.
进阶变体
外企场景- arrow_right_alt
Count good pairs where nums1[i] % (nums2[j] + k) == 0 instead of multiplication by k.
- arrow_right_alt
Find maximum number of good pairs instead of total count.
- arrow_right_alt
Extend to 3 arrays where a triple (i, j, l) is good if nums1[i] % (nums2[j] * nums3[l] * k) == 0.