LeetCode 题解工作台
优质数对的总数 I
给你两个整数数组 nums1 和 nums2 ,长度分别为 n 和 m 。同时给你一个 正整数 k 。 如果 nums1[i] 可以除尽 nums2[j] * k ,则称数对 (i, j) 为 优质数对 ( 0 , 0 )。 返回 优质数对 的总数。 示例 1: 输入: nums1 = [1,3,4…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数组·哈希·扫描
答案摘要
我们直接枚举所有的数位 $(x, y)$,判断是否满足 $x \bmod (y \times k) = 0$,如果满足则答案加一。 枚举结束后,返回答案即可。
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 <= 501 <= nums1[i], nums2[j] <= 501 <= k <= 50
解题思路
方法一:暴力枚举
我们直接枚举所有的数位 ,判断是否满足 ,如果满足则答案加一。
枚举结束后,返回答案即可。
时间复杂度 ,其中 和 分别是数组 和 的长度。空间复杂度 。
class Solution:
def numberOfPairs(self, nums1: List[int], nums2: List[int], k: int) -> int:
return sum(x % (y * k) == 0 for x in nums1 for y in nums2)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * m) in the naive scan, but using hash lookup for nums2 reduces repeated divisor checks. Space complexity is O(m) for the hash table storing nums2 counts. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ask about using hash tables to optimize repeated divisor checks in nums2.
- question_mark
Check if the candidate considers array scanning versus nested loops for efficiency.
- question_mark
Probe understanding of how small constraints affect the choice of brute-force or optimized approach.
常见陷阱
外企场景- error
Forgetting to multiply nums2[j] by k before checking divisibility.
- error
Double-counting pairs if using hash table incorrectly.
- error
Assuming sorted arrays when order does not matter, leading to wrong indexing.
进阶变体
外企场景- arrow_right_alt
Consider counting good pairs with nums1[i] divisible by nums2[j] + k instead of multiplied.
- arrow_right_alt
Modify the problem to handle large arrays requiring more optimized divisor counting strategies.
- arrow_right_alt
Count good pairs where nums1[i] modulo nums2[j] equals k, changing the divisibility condition.