LeetCode 题解工作台

优质数对的总数 I

给你两个整数数组 nums1 和 nums2 ,长度分别为 n 和 m 。同时给你一个 正整数 k 。 如果 nums1[i] 可以除尽 nums2[j] * k ,则称数对 (i, j) 为 优质数对 ( 0 , 0 )。 返回 优质数对 的总数。 示例 1: 输入: nums1 = [1,3,4…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数组·哈希·扫描

bolt

答案摘要

我们直接枚举所有的数位 $(x, y)$,判断是否满足 $x \bmod (y \times k) = 0$,如果满足则答案加一。 枚举结束后,返回答案即可。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个整数数组 nums1nums2,长度分别为 nm。同时给你一个正整数 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 <= 50
  • 1 <= nums1[i], nums2[j] <= 50
  • 1 <= k <= 50
lightbulb

解题思路

方法一:暴力枚举

我们直接枚举所有的数位 (x,y)(x, y),判断是否满足 xmod(y×k)=0x \bmod (y \times k) = 0,如果满足则答案加一。

枚举结束后,返回答案即可。

时间复杂度 O(m×n)O(m \times n),其中 mmnn 分别是数组 nums1\textit{nums1}nums2\textit{nums2} 的长度。空间复杂度 O(1)O(1)

1
2
3
4
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)
speed

复杂度分析

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

面试官常问的追问

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

warning

常见陷阱

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

swap_horiz

进阶变体

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

help

常见问题

外企场景

优质数对的总数 I题解:数组·哈希·扫描 | LeetCode #3162 简单