lc1237 Find Positive Integer Solution for a Given Equation
Question
Given a callable function f(x, y) with a hidden formula and a value z, reverse engineer the formula and return all positive integer pairs x and y where f(x,y) == z. You may return the pairs in any order.
While the exact formula is hidden, the function is monotonically increasing, i.e.:
f(x, y) < f(x + 1, y)
f(x, y) < f(x, y + 1)
The function interface is defined like this:
1 | interface CustomFunction { |
We will judge your solution as follows:
The judge has a list of 9 hidden implementations of CustomFunction, along with a way to generate an answer key of all valid pairs for a specific z.
The judge will receive two inputs: a function_id (to determine which implementation to test your code with), and the target z.
The judge will call your findSolution and compare your results with the answer key.
If your results match the answer key, your solution will be Accepted.
1 | Example 1: |
Solution 01
So, can i call the funtion f like this?
customfunction.f(x,y);
Ok, the z ranges from 1 to 100. And x and y range from 1 to 1000.
So. That’s not a huge amount of data.
The easy idea it to try each xy pairs. I need try a million time to get all pairs.
Considering that f is a incresing function for both x and y. I think i can use the dichotomy to find pairs. The time complexity of this solution is O(x log(y)); x times log y.
1 | class Solution { |
solution 02
// x=500 y=100; f’s return value is z.
// And than, x goes up to 501.
// x=501 y!=100-1000
// Beacuse function f is increasing. So y can’t be a bigger number than 100.
// Based on this idea, i can reduce the time complexity to O(x+y)
1 | class Solution { |