LeetCode 题解工作台
双模幂运算
给你一个下标从 0 开始的二维数组 variables ,其中 variables[i] = [a i , b i , c i, m i ] ,以及一个整数 target 。 如果满足以下公式,则下标 i 是 好下标 : 0 ((a i b i % 10) c i ) % m i == target…
3
题型
5
代码语言
3
相关题
当前训练重点
中等 · 数组·数学
答案摘要
我们直接根据题目描述模拟即可。对于幂运算取模,我们可以使用快速幂来加速运算。 时间复杂度 $O(n \times \log M)$,其中 为数组 的长度;而 为 和 中的最大值,本题中 $M \le 10^3$。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·数学 题型思路
题目描述
给你一个下标从 0 开始的二维数组 variables ,其中 variables[i] = [ai, bi, ci, mi],以及一个整数 target 。
如果满足以下公式,则下标 i 是 好下标:
0 <= i < variables.length((aibi % 10)ci) % mi == target
返回一个由 好下标 组成的数组,顺序不限 。
示例 1:
输入:variables = [[2,3,3,10],[3,3,3,1],[6,1,1,4]], target = 2 输出:[0,2] 解释:对于 variables 数组中的每个下标 i : 1) 对于下标 0 ,variables[0] = [2,3,3,10] ,(23 % 10)3 % 10 = 2 。 2) 对于下标 1 ,variables[1] = [3,3,3,1] ,(33 % 10)3 % 1 = 0 。 3) 对于下标 2 ,variables[2] = [6,1,1,4] ,(61 % 10)1 % 4 = 2 。 因此,返回 [0,2] 作为答案。
示例 2:
输入:variables = [[39,3,1000,1000]], target = 17 输出:[] 解释:对于 variables 数组中的每个下标 i : 1) 对于下标 0 ,variables[0] = [39,3,1000,1000] ,(393 % 10)1000 % 1000 = 1 。 因此,返回 [] 作为答案。
提示:
1 <= variables.length <= 100variables[i] == [ai, bi, ci, mi]1 <= ai, bi, ci, mi <= 1030 <= target <= 103
解题思路
方法一:模拟 + 快速幂
我们直接根据题目描述模拟即可。对于幂运算取模,我们可以使用快速幂来加速运算。
时间复杂度 ,其中 为数组 的长度;而 为 和 中的最大值,本题中 。空间复杂度 。
class Solution:
def getGoodIndices(self, variables: List[List[int]], target: int) -> List[int]:
return [
i
for i, (a, b, c, m) in enumerate(variables)
if pow(pow(a, b, 10), c, m) == target
]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate should be able to break down the modular arithmetic into clear steps and explain how modular exponentiation works.
- question_mark
A good approach will involve optimizing the power calculations using efficient algorithms such as fast exponentiation.
- question_mark
Look for a solution that correctly handles edge cases, such as large values of `ai`, `bi`, and `mi`.
常见陷阱
外企场景- error
Candidates may fail to correctly apply modular arithmetic or overlook the second modulo operation, which could lead to incorrect results.
- error
Some candidates might use brute-force exponentiation, which can be inefficient for large values of `bi`.
- error
Incorrectly handling edge cases like when `target` is 0 or when the `variables` array has fewer than expected elements could lead to errors.
进阶变体
外企场景- arrow_right_alt
Increase the size of the array and test the algorithm's scalability with higher values of `ai`, `bi`, `ci`, and `mi`.
- arrow_right_alt
Test cases where the `target` is much smaller or larger than the computed results to check if the solution handles a wide range of values.
- arrow_right_alt
Test cases where all indices are good or none are good, to see if the solution properly handles these extremes.