leetcode 1237. Find Positive Integer Solution for a Given Equation 解法 python

一.问题描述

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 <= 9
  • 1 <= z <= 100
  • It's guaranteed that the solutions of f(x, y) == z will be on the range 1 <= x, y <= 1000
  • It's also guaranteed that f(x, y) will fit in 32 bit signed integer if 1 <= 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
                

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值