程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(2)

LeetCode-Python-1237.找出给定方程的正整数解

发布于2019-10-28 15:46     阅读(1254)     评论(0)     点赞(25)     收藏(0)


 

出一个函数  f(x, y) 和一个目标结果 z,请你计算方程 f(x,y) == z 所有可能的正整数 数对 x 和 y

给定函数是严格单调的,也就是说:

  • f(x, y) < f(x + 1, y)
  • f(x, y) < f(x, y + 1)

函数接口定义如下:

interface CustomFunction {
public:
  // Returns positive integer f(x, y) for any given positive integer x and y.
  int f(int x, int y);
};

如果你想自定义测试,你可以输入整数 function_id 和一个目标结果 z 作为输入,其中 function_id 表示一个隐藏函数列表中的一个函数编号,题目只会告诉你列表中的 2个函数。  

你可以将满足条件的 结果数对 按任意顺序返回。

 

示例 1:

输入:function_id = 1, z = 5
输出:[[1,4],[2,3],[3,2],[4,1]]
解释:function_id = 1 表示 f(x, y) = x + y

示例 2:

输入:function_id = 2, z = 5
输出:[[1,5],[5,1]]
解释:function_id = 2 表示 f(x, y) = x * y

 

提示:

  • 1 <= function_id <= 9
  • 1 <= z <= 100
  • 题目保证 f(x, y) == z 的解处于 1 <= x, y <= 1000 的范围内。
  • 在 1 <= x, y <= 1000 的前提下,题目保证 f(x, y) 是一个 32 位有符号整数。

思路:

严格递增,暗示二分。

  1. """
  2. This is the custom function interface.
  3. You should not implement it, or speculate about its implementation
  4. class CustomFunction:
  5. # Returns f(x, y) for any given positive integers x and y.
  6. # Note that f(x, y) is increasing with respect to both x and y.
  7. # i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1)
  8. def f(self, x, y):
  9. """
  10. class Solution(object):
  11. def findSolution(self, customfunction, z):
  12. """
  13. :type num: int
  14. :type z: int
  15. :rtype: List[List[int]]
  16. """
  17. res = []
  18. for x in range(1, 1001):
  19. left, right = 1, 1000
  20. while left <= right:
  21. mid = (left + right) // 2
  22. t = customfunction.f(x, mid)
  23. if t == z:
  24. res.append([x, mid])
  25. break
  26. elif t > z:
  27. right = mid - 1
  28. elif t < z:
  29. left = mid + 1
  30. return res

 



所属网站分类: 技术文章 > 博客

作者:放羊人

链接:https://www.pythonheidong.com/blog/article/147083/7421fc2bf9357f760e91/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

25 0
收藏该文
已收藏

评论内容:(最多支持255个字符)