一.问题描述
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
二.解题思路
就是找到所有经过f函数处理之后返回值为z的两个数下x,y.
由f函数的定义我们可以看出f函数是一个递增函数。
因此想到用二分法,但是发现二分法甚至可能比线性搜索要更复杂。
因为f(x,y)大于z的时候,因为x和y是一次排除一半,因此有可能x大了也有可能y大了,比如1+5和2+4都等于6,但是很可能我们二分的时候 target为6,f 大了,然后high从8变成4,然后1+4<6, 1变成2,虽然满足了target等于6,但是漏了1+5的情况。
不要直接穷举所有x,y,这样子完全没利用到f的特性,并且复杂度为O(N*N)
直接线性搜索,x从1到1000,y从1000~1同时进行搜索。
如果 f(x,y)>z,说明y大了,y减1,
如果f(x,y)<z,说明x小了,x加1,
相等就保存,然后x+1继续搜索。
有点利用二分搜索的思想?
时间复杂度:O(N)
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
"""
This is the custom function interface.
You should not implement it, or speculate about its implementation
class CustomFunction:
# 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)
def f(self, x, y):
"""
class Solution:
def findSolution(self, customfunction: 'CustomFunction', z: int) -> List[List[int]]:
rst=[]
x,y=1,1000
while x<=1000 and y>=1 :
f_xy=customfunction.f(x,y)
if f_xy>z:
y-=1
elif f_xy<z:
x+=1
else:
rst.append([x,y])
x+=1
return rst
本文介绍了一种高效算法,用于查找所有正整数对(x, y),使得给定函数f(x, y)的值等于目标值z。通过线性搜索而非二分搜索,避免了遗漏解的问题,确保了所有符合条件的整数对都能被找到。
821

被折叠的 条评论
为什么被折叠?



