1. 问题描述:
给出一个函数 f(x, y) 和一个目标结果 z,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y。
给定函数是严格单调的,也就是说:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
函数接口定义如下:
interface CustomFunction {
public:
// Returns positive integer f(x, y) for any given positive integer x and y.
int f(int x, int y);
};
如果你想自定义测试,你可以输入整数 function_id 和一个目标结果 z 作为输入,其中 function_id 表示一个隐藏函数列表中的一个函数编号,题目只会告诉你列表中的 2 个函数。
你可以将满足条件的 结果数对按任意顺序返回。
示例 1:
输入:function_id = 1, z = 5
输出:[[1,4],[2,3],[3,2],[4,1]]
解释:function_id = 1 表示 f(x, y) = x + y
示例 2:
输入:function_id = 2, z = 5
输出:[[1,5],[5,1]]
解释:function_id = 2 表示 f(x, y) = x * y
提示:
1 <= function_id <= 9
1 <= z <= 100
题目保证 f(x, y) == z 的解处于 1 <= x, y <= 1000 的范围内。
在 1 <= x, y <= 1000 的前提下,题目保证 f(x, y) 是一个 32 位有符号整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-positive-integer-solution-for-a-given-equation
2. 思路分析:
① 首先比较容易想到是暴力破解,在给定的x,y范围内进行计算看是否通过函数得到z,使用暴力破解可以使用python中的列表生成表达式返回即可,但是这种解决方法耗时比较大,对于上面的数据的较小规模还是可以解决的
② 除了使用暴力破解的方法之外,在领扣的题解中看到可以使用双指针的方法来进行解决,一开始的时候固定x与y的值,为1与最大范围1000,使用函数对当前的x与y的值进行计算,看是否与z相等,假如小了那么x加1往右移动,假如大了y减1往左移动,相等之后两者同时移动最后,这个双指针的思路还是挺好的,起码不会耗时太多了
3. 代码如下:
双指针:
class Solution:
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
res = []
x, y = 1, 10000
while x <= z and y >= 1:
temp = customfunction.f(x, y)
if temp < z:
x += 1
elif temp > z:
y -= 1
else:
res.append([x, y])
x += 1
y -= 1
return res
暴力破解:
class Solution:
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
return [[x,y]for x in range(1,z+1) for y in range(1,z+1) if customfunction.f(x,y) == z]