Given a function f(x, y) and a value z, return all positive integer pairs x and y where f(x,y) == z.
The function is constantly increasing, i.e.:
f(x, y) < f(x + 1, y)f(x, y) < f(x, y + 1)
The function interface is defined like this:
interface CustomFunction {
public:
// Returns positive integer f(x, y) for any given positive integer x and y.
int f(int x, int y);
};
For custom testing purposes you’re given an integer function_id and a target z as input, where function_id represent one function from an secret internal list, on the examples you’ll know only two functions from the list.
You may return the solutions in any order.
Example 1:
Input: function_id = 1, z = 5 Output: [[1,4],[2,3],[3,2],[4,1]] Explanation: function_id = 1 means that f(x, y) = x + y
Example 2:
Input: function_id = 2, z = 5 Output: [[1,5],[5,1]] Explanation: function_id = 2 means that f(x, y) = x * y
Constraints:
1 <= function_id <= 91 <= z <= 100- It’s guaranteed that the solutions of
f(x, y) == zwill be on the range1 <= x, y <= 1000 - It’s also guaranteed that
f(x, y)will fit in 32 bit signed integer if1 <= x, y <= 1000
Solution1 : Brute Force
Time complexity: O(1000*1000)
Space complexity: O(1)
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Author: Huahua class Solution { public: vector<vector<int>> findSolution(CustomFunction& customfunction, int z) { vector<vector<int>> ans; for (int x = 1; x <= 1000; ++x) { if (customfunction.f(x, 1) > z) break; for (int y = 1; y <= 1000; ++y) { int t = customfunction.f(x, y); if (t > z) break; if (t == z) ans.push_back({x, y}); } } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.


Be First to Comment