力扣1237. 找出给定方程的正整数解

一、题目描述:给你一个函数  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 some positive integer f(x, y) for two positive integers x and y based on a formula.
  int f(int x, int y);
};

 二、解决方法:

语言:Java

1.暴力解法:

class Solution {
	public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
		List<List<Integer>> ans = new ArrayList<>();
		for (int i = 1; i < 1001; i++) {
			for (int j = 1; j < 1001; j++) {
				if (customfunction.f(i, j) == z) {
					ans.add(Arrays.asList(new Integer[] { i, j }));
				}
			}
		}
		return ans;
	}
}

2.二分法:

class Solution {
    public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
		
        List<List<Integer>> res = new ArrayList<>();
        for(int i=1;i<=1000;i++){
            int left = 1;
            int right = 1000;
            while (left <= right){
                int mid = (left+right)/2;
                int temp = customfunction.f(i,mid);
                if(temp==z){
                    res.add(Arrays.asList(new Integer[] { i,mid}));
                    break;
                    }else if (temp>z){
                        right = mid-1;
                    }else{
                        left = mid+1;
                    }
            }
        }  
        return res; 
    }
}

3.双指针解法:

class Solution {
    public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {
        List<List<Integer>> res = new ArrayList<>();
        int left = 1;
        int right = 1000;
        while (left <= 1000 && right >= 1) {
            int temp = customfunction.f(left,right);
            if (temp == z) {
                res.add(Arrays.asList(new Integer[] { left,right}));
                left++;
            } else if (temp > z) {
                right--;
            } else {
                left++;
            }
        }
        return res;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值