0%

找出给定方程的正整数解

题目地址

难度:

题目描述:

给出一个函数 f(x, y) 和一个目标结果 z,请你计算方程 f(x,y) == z 所有可能的正整数 数对 xy

给定函数是严格单调的,也就是说:

f(x, y) < f(x + 1, y)

f(x, y) < f(x, y + 1)

函数接口定义如下:

1
2
3
4
5
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:

1
2
3
输入:function_id = 1, z = 5
输出:[[1,4],[2,3],[3,2],[4,1]]
解释:function_id = 1 表示 f(x, y) = x + y

示例2:

1
2
3
输入: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 位有符号整数。

🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️解题过程🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️🙋‍♂️
解题过程:

思路:

对数对的第一个元素i的可能取值从1开始遍历,对每次取值从1遍历第二个元素j,如果函数值大于z就break,表示取值i时的数对已经遍历完成,终止程序的条件是f(i,1)的值大于z。

c++代码:(执行用时0ms,击败100.00%,内存消耗6.7M,击败9.50%)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
* // 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>> result;
vector<int> tmp(2,0);
int i=0,j=0;
while(++i){
while(++j){
if(customfunction.f(i,j)==z){
tmp[0]=i;
tmp[1]=j;
result.emplace_back(tmp);
}else if(customfunction.f(i,j)>z){
break;
}
}
j=0;
if(customfunction.f(i,1)>z){
break;
}
}
return result;
}
};
⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳总 结⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳⏳
总结:

没有官方题解,正合我意该睡觉了😪,也还行比较简单。

------------- THE END! THANKS! -------------