zoukankan      html  css  js  c++  java
  • 【leetcode】1237. Find Positive Integer Solution for a Given Equation

    题目如下:

    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

    解题思路:看到1 <= x, y <= 1000时,就可以意识到O(n^2)的复杂度是可以接受的,那么两层循环计算一下吧。

    代码如下:

    """
       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(object):
        def findSolution(self, customfunction, z):
            """
            :type num: int
            :type z: int
            :rtype: List[List[int]]
            """
            res = []
            for x in range(1,1001):
                for y in range(1,1001):
                    if customfunction.f(x,y) == z:
                        res.append([x,y])
                    elif customfunction.f(x,y) > z:
                        break
            return res
            
  • 相关阅读:
    【源码解析】Flink 是如何处理迟到数据
    Flink assignAscendingTimestamps 生成水印的三个重载方法
    【翻译】生成 Timestamps / Watermarks
    【翻译】The Broadcast State Pattern(广播状态)
    基于Broadcast 状态的Flink Etl Demo
    git 更新fork的远程仓库
    Flink 在IDEA执行时的webui
    配置ssh免密,仍需要密码
    第二章 Kubernetes进阶之使用二进制包部署集群
    Kubernetes之Ingress
  • 原文地址:https://www.cnblogs.com/seyjs/p/11758483.html
Copyright © 2011-2022 走看看