[leetcode] 1237. Find Positive Integer Solution for a Given Equation

Description

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

分析

题目的意思是:给定方程,求出正整数的解。我看了一下别人的求解,因为这个方程是不透明的,所以需要在[0,z]上遍历一个一个的找出来就行了,对于每个值i,可以用二分法来找出合适的值。

代码

"""
   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]]:
        res=[]
        for i in range(z):
            l=1
            h=z+1
            while(l<=h):
                mid=l+(h-l)//2
                if(customfunction.f(i+1,mid)==z):
                    res.append([i+1,mid])
                    break
                elif(customfunction.f(i+1,mid)>z):
                    h=mid-1
                else:
                    l=mid+1
        return res

参考文献

[LeetCode] Easy 3 python solutions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值