1237. 找出給定方程的正整數解
給出一個函式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
暴力
""" This is the custom function interface. You should not implement it, or speculate about its implementation class CustomFunction: # Returns f(x, y) for any given positive integers x and y. # Note that f(x, y) is increasing with respect to both x and y. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) def f(self, x, y):""" class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: res=[] for i in range(1,z+1): for j in range(1,z+1): if customfunction.f(i,j)==z: res.append([i,j]) return res
二分
""" This is the custom function interface. You should not implement it, or speculate about its implementation class CustomFunction: # Returns f(x, y) for any given positive integers x and y. # Note that f(x, y) is increasing with respect to both x and y. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) def f(self, x, y): """ class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: res=[] for i in range(1,z+1): l=1 r=z while l<=r: mid=(l+r)>>1 fun=customfunction.f(i,mid) if fun==z: res.append([i,mid]) break elif fun<z: l=mid+1 else: r=mid-1 return res
利用單調性
""" This is the custom function interface. You should not implement it, or speculate about its implementation class CustomFunction: # Returns f(x, y) for any given positive integers x and y. # Note that f(x, y) is increasing with respect to both x and y. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) def f(self, x, y): """ class Solution: def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]: y=z for x in range(1,z+1): while y: if customfunction.f(x,y)<=z: if customfunction.f(x,y)==z: yield [x,y] break y-=1