美文网首页
leetcode每日一题(1237找出给定方程的正整数解)

leetcode每日一题(1237找出给定方程的正整数解)

作者: 韩其凯 | 来源:发表于2023-02-17 11:14 被阅读0次
  1. 题意
  2. 思路:由于f是单调递增函数,我们可以从x = 1, y = 1000开始,表示在横坐标为[x, 1000]以及纵坐标为[1, y]的举行范围内搜索答案。分类讨论:
  • 如果f(x, y) < z,那么对于任意的y' < y,都有f(x, y') < f(x, y) < z,这说明固定x,无论怎样枚举y,都无法找到答案,那么将x加一,缩小搜索范围;
  • 如果f(x, y) > z,那对于任意x' > x,都有f(x', y) > f(x, y) > z,这说明固定y枚举其余x无法找到答案,那么将y减一,缩小搜索范围;
  • 如果f(x, y) = z,那么记录答案,同情况1一样,将x加一。由于f(x + 1, y) > f(x, y) = z,根据情况2,可以同时将y减一。
  • 不断循环直到x > 1000y < 1为止,此时搜索范围为空。
  1. 代码:
    C++代码:
/*
 * // This is the custom function interface.
 * // You should not implement it, or speculate about its implementation
 * class CustomFunction {
 * public:
 *     // 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)
 *     int f(int x, int y);
 * };
 */

class Solution {
public:
    vector<vector<int>> findSolution(CustomFunction& f, int z) {
        vector<vector<int>> res;
        int i = 1, j = 1000;
        while(i <= 1000 && j >= 1) {
            if (f.f(i, j) == z) res.push_back({i ++, j --});
            if (f.f(i, j) > z) --j;
            if (f.f(i, j) < z) ++i;
        }
        return res;

        
    }
};

Python代码

"""
   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: 'f', z: int) -> List[List[int]]:
        res = []
        i, j = 1, 1000
        while(i <=1000 and j >= 1):
            if customfunction.f(i, j) == z:
                res.append([i, j])
                i += 1
                j += 1
            if customfunction.f(i, j) < z:   i += 1
            if customfunction.f(i, j) > z:   j -= 1
        return res
  1. 分析
  • 时间复杂度:O(C), C <= 1000
  • 空间复杂第:O(1)

相关文章

网友评论

      本文标题:leetcode每日一题(1237找出给定方程的正整数解)

      本文链接:https://www.haomeiwen.com/subject/jnbmkdtx.html