题目描述
给出一个函数 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 个函数。
你可以将满足条件的答案按任意顺序返回。
样例
输入:function_id = 1, z = 5
输出:[[1,4],[2,3],[3,2],[4,1]]
解释:function_id = 1 表示 f(x, y) = x + y
输入: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 位有符号整数。
算法
(暴力枚举) $O(n^2)$
- 枚举
x
和y
,调用接口判断f(x, y)
是否等于z
。 - 如果等于
z
,则加入答案中,如果大于z
,则终止掉内层循环。
时间复杂度
- 最坏情况下,需要判断每一个数对,故时间复杂度为 $O(n^2)$。
空间复杂度
- 需要存储答案,故空间复杂度也为 $O(n^2)$。
C++ 代码
/*
* // This is the custom function interface.
* // You should not implement it, or speculate about its implementation
* class CustomFunction {
* public:
* // 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)
* int f(int x, int y);
* };
*/
class Solution {
public:
vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
vector<vector<int>> ans;
for (int x = 1; x <= 1000; x++)
for (int y = 1; y <= 1000; y++) {
if (customfunction.f(x, y) == z) {
ans.push_back({x, y});
} else if (customfunction.f(x, y) > z) {
break;
}
}
return ans;
}
};
可以枚举x 二分y吧
当然可以二分,但这里暴力可以过,周赛的时候要争分夺秒hh