给出一个函数 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
代码
/** // 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)* public int f(int x, int y);* };*/class Solution {public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {List<List<Integer>> res=new ArrayList<>();for(int i=1;i<=z;i++)//尝试不同的x{int l=1,r=z;while (l<=r)//二分查找符合的y{int mid=(r-l)/2+l;if(customfunction.f(i,mid)==z)//找到了结果{ArrayList<Integer> temp=new ArrayList<>();temp.add(i); temp.add(mid);res.add(temp);break;}else if(customfunction.f(i,mid)<z)l=mid+1;else r=mid-1;}}return res;}
}