题目来源
题目描述
题目解析
难得是看懂题目
类似题目:搜索二维矩阵
x=1,y=1,相当于矩阵左上角,x=1000,y=1000,相当于矩阵右下角
dalao
暴力
/*
* // 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 i = 1; i < z; ++i) {
for (int j = 1; j < z; ++j) {
int tmp = customfunction.f(i, j);
if(tmp == z){
ans.push_back({i, j});
}else if(tmp > z){
break;
}
}
}
return ans;
}
};
时间复杂度 O(Z^2)
二分法
因为有序,所以可以二分
固定一边,二分查找另一边:
- 枚举从 1 到 1000 的每个 x 值。对于每个 x 值,在区间 [1, 1000] 内使用二分查找找到 y 的值。
不推荐使用这个做法,因为只利用到了函数 f 对 y 变量是递增的,没有利用到对 x 也是这样。
代码
class Solution {
public:
vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
vector<vector<int>> ans;
int x = 1;
int y = z;
for (int i = 1; i <= 1000; i++) {
int l = 1;
int r = 1000;
while (l <= r) {
int mid = l + (r - l) / 2;
if (customfunction.f(i, mid) < z) {
l = mid + 1;
} else if (customfunction.f(i, mid) > z){
r = mid - 1;
} else {
ans.push_back({i, mid});
l = mid + 1;
r = mid - 1;
}
}
}
return ans;
}
};