LC1237. 找出给定方程的正整数解

1. 题目

给你一个函数 f(x, y) 和一个目标结果 z,函数公式未知,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y。满足条件的结果数对可以按任意顺序返回。

尽管函数的具体式子未知,但它是单调递增函数,也就是说:
f ( x , y ) < f ( x + 1 , y ) f(x, y) < f(x + 1, y) f(x,y)<f(x+1,y)
f ( x , y ) < f ( x , y + 1 ) f(x, y) < f(x, y + 1) f(x,y)<f(x,y+1)

函数接口定义如下:

interface CustomFunction {
public:
  // Returns some positive integer f(x, y) for two positive integers x and y based on a formula.
  int f(int x, int y);
};

你的解决方案将按如下规则进行评判:

  1. 判题程序有一个由 CustomFunction 的 9 种实现组成的列表,以及一种为特定的 z 生成所有有效数对的答案的方法。
  2. 判题程序接受两个输入:function_id(决定使用哪种实现测试你的代码)以及目标结果 z 。
  3. 判题程序将会调用你实现的 findSolution 并将你的结果与答案进行比较。
  4. 如果你的结果与答案相符,那么解决方案将被视作正确答案,即 Accepted 。

链接

2. 参考

函数为单调递增,因此我们从小到大进行枚举 x x x,并且从大到小枚举 y y y,当固定 x x x 时,不需要重头开始枚举所有的 y y y,只需要从上次结束的值开始枚举即可。

3. 代码

class Solution:
    def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
        ans = []
        y = 1000
        for x in range(1, 1001):
            while y and customfunction.f(x, y) > z:
                y -= 1
            if y == 0:
                break
            if customfunction.f(x, y) == z:
                ans.append([x, y])
        return ans
  1. 时间限制:
    for循环 判断 循环
    while循环仅判断

猜你喜欢

转载自blog.csdn.net/deer2019530/article/details/129105191