一、题目描述:给你一个函数 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 some positive integer f(x, y) for two positive integers x and y based on a formula.
int f(int x, int y);
};
二、解决方法:
语言:Java
1.暴力解法:
class Solution {
public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
List<List<Integer>> ans = new ArrayList<>();
for (int i = 1; i < 1001; i++) {
for (int j = 1; j < 1001; j++) {
if (customfunction.f(i, j) == z) {
ans.add(Arrays.asList(new Integer[] { i, j }));
}
}
}
return ans;
}
}
2.二分法:
class Solution {
public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
List<List<Integer>> res = new ArrayList<>();
for(int i=1;i<=1000;i++){
int left = 1;
int right = 1000;
while (left <= right){
int mid = (left+right)/2;
int temp = customfunction.f(i,mid);
if(temp==z){
res.add(Arrays.asList(new Integer[] { i,mid}));
break;
}else if (temp>z){
right = mid-1;
}else{
left = mid+1;
}
}
}
return res;
}
}
3.双指针解法:
class Solution {
public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
List<List<Integer>> res = new ArrayList<>();
int left = 1;
int right = 1000;
while (left <= 1000 && right >= 1) {
int temp = customfunction.f(left,right);
if (temp == z) {
res.add(Arrays.asList(new Integer[] { left,right}));
left++;
} else if (temp > z) {
right--;
} else {
left++;
}
}
return res;
}
}