LeetCode 题解工作台
最接近的因数
给你一个整数 num ,请你找出同时满足下面全部要求的两个整数: 两数乘积等于 num + 1 或 num + 2 以绝对差进行度量,两数大小最接近 你可以按任意顺序返回这两个整数。 示例 1: 输入: num = 8 输出: [3,3] 解释: 对于 num + 1 = 9,最接近的两个因数是 3…
1
题型
4
代码语言
3
相关题
当前训练重点
中等 · 数学·driven
答案摘要
我们设计一个函数 ,该函数返回乘积等于 的两个数,且这两个数的差的绝对值最小。我们可以从 开始枚举 ,如果 能被 整除,那么 就是另一个因数,此时我们就找到了一个乘积等于 的两个因数,我们将其返回即可。否则我们减小 的值,继续枚举。 接下来,我们只需要分别计算 $f(num + 1)$ 和 $f(num + 2)$,然后比较两个函数的返回值,返回差的绝对值更小的那个即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你一个整数 num,请你找出同时满足下面全部要求的两个整数:
- 两数乘积等于
num + 1或num + 2 - 以绝对差进行度量,两数大小最接近
你可以按任意顺序返回这两个整数。
示例 1:
输入:num = 8 输出:[3,3] 解释:对于 num + 1 = 9,最接近的两个因数是 3 & 3;对于 num + 2 = 10, 最接近的两个因数是 2 & 5,因此返回 3 & 3 。
示例 2:
输入:num = 123 输出:[5,25]
示例 3:
输入:num = 999 输出:[40,25]
提示:
1 <= num <= 10^9
解题思路
方法一:枚举
我们设计一个函数 ,该函数返回乘积等于 的两个数,且这两个数的差的绝对值最小。我们可以从 开始枚举 ,如果 能被 整除,那么 就是另一个因数,此时我们就找到了一个乘积等于 的两个因数,我们将其返回即可。否则我们减小 的值,继续枚举。
接下来,我们只需要分别计算 和 ,然后比较两个函数的返回值,返回差的绝对值更小的那个即可。
时间复杂度 ,空间复杂度 。其中 是给定的整数。
class Solution:
def closestDivisors(self, num: int) -> List[int]:
def f(x):
for i in range(int(sqrt(x)), 0, -1):
if x % i == 0:
return [i, x // i]
a = f(num + 1)
b = f(num + 2)
return a if abs(a[0] - a[1]) < abs(b[0] - b[1]) else b
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate understands the properties of divisors and can apply them efficiently.
- question_mark
Candidate can optimize solutions based on mathematical properties, such as limiting the divisor range to the square root.
- question_mark
Candidate can explain how they minimized the absolute difference and why that’s the optimal approach.
常见陷阱
外企场景- error
Not limiting the divisor search to the square root of num + 1 and num + 2, leading to inefficient solutions.
- error
Overcomplicating the problem by checking too many divisor pairs without focusing on minimizing the absolute difference.
- error
Confusing the problem by returning divisors without considering the smallest absolute difference.
进阶变体
外企场景- arrow_right_alt
Allow for multiple valid pairs of divisors with different absolute differences, but still require choosing the pair with the smallest difference.
- arrow_right_alt
Extend the problem to find the closest divisors for num + 1, num + 2, and num + 3.
- arrow_right_alt
Add constraints that require finding the pair of divisors that are both prime.