LeetCode 题解工作台
统计可以被 K 整除的下标对数目
给你一个下标从 0 开始、长度为 n 的整数数组 nums 和一个整数 k ,返回满足下述条件的下标对 (i, j) 的数目: 0 且 nums[i] * nums[j] 能被 k 整除。 示例 1: 输入: nums = [1,2,3,4,5], k = 2 输出: 7 解释: 共有 7 对下标的…
3
题型
0
代码语言
3
相关题
当前训练重点
困难 · 数组·数学
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始、长度为 n 的整数数组 nums 和一个整数 k ,返回满足下述条件的下标对 (i, j) 的数目:
0 <= i < j <= n - 1且nums[i] * nums[j]能被k整除。
示例 1:
输入:nums = [1,2,3,4,5], k = 2 输出:7 解释: 共有 7 对下标的对应积可以被 2 整除: (0, 1)、(0, 3)、(1, 2)、(1, 3)、(1, 4)、(2, 3) 和 (3, 4) 它们的积分别是 2、4、6、8、10、12 和 20 。 其他下标对,例如 (0, 2) 和 (2, 4) 的乘积分别是 3 和 15 ,都无法被 2 整除。
示例 2:
输入:nums = [1,2,3,4], k = 5 输出:0 解释:不存在对应积可以被 5 整除的下标对。
提示:
1 <= nums.length <= 1051 <= nums[i], k <= 105
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to optimize brute force approaches.
- question_mark
Understanding of number theory and modular arithmetic.
- question_mark
Familiarity with efficient frequency counting techniques.
常见陷阱
外企场景- error
Using a brute force approach without optimizing divisibility checks.
- error
Overlooking how modular arithmetic can simplify the solution.
- error
Not considering edge cases where no valid pairs exist, like when the product is never divisible by k.
进阶变体
外企场景- arrow_right_alt
What if k is a prime number?
- arrow_right_alt
How would the solution change if we wanted to count pairs whose product is divisible by a prime factor of k?
- arrow_right_alt
Can this solution be adapted for non-zero index-based array pairs?