leetcode:1237. 找出给定方程的正整数解

题目来源

LEETCODE

题目描述

在这里插入图片描述
在这里插入图片描述

题目解析

难得是看懂题目

类似题目:搜索二维矩阵
x=1,y=1,相当于矩阵左上角,x=1000,y=1000,相当于矩阵右下角
在这里插入图片描述
dalao

暴力

/*
 * // 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& customfunction, int z) {
    vector<vector<int>> ans;
    for (int i = 1; i < z; ++i) {
        for (int j = 1; j < z; ++j) {
            int tmp = customfunction.f(i, j);
            if(tmp == z){
               ans.push_back({i, j});
            }else if(tmp > z){
                break;
            }
        }
    }

    return ans;
    }
};

在这里插入图片描述

时间复杂度 O(Z^2)

二分法

因为有序,所以可以二分
在这里插入图片描述
固定一边,二分查找另一边:

  • 枚举从 1 到 1000 的每个 x 值。对于每个 x 值,在区间 [1, 1000] 内使用二分查找找到 y 的值。

不推荐使用这个做法,因为只利用到了函数 f 对 y 变量是递增的,没有利用到对 x 也是这样。
代码

class Solution {
public:
    vector<vector<int>> findSolution(CustomFunction& customfunction, int z) {
        vector<vector<int>> ans;
        int x = 1;
        int y = z;

        for (int i = 1; i <= 1000; i++) {
            int l = 1;
            int r = 1000;

            while (l <= r) {
                int mid = l + (r - l) / 2;
                if (customfunction.f(i, mid) < z) {
                    l = mid + 1;
                } else if (customfunction.f(i, mid) > z){
                    r = mid - 1;
                } else {
                    ans.push_back({i, mid});
                    l = mid + 1;
                    r = mid - 1;
                }
            }
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值