日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode1237. 找出给定方程的正整数解(二分法)

發布時間:2023/11/29 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode1237. 找出给定方程的正整数解(二分法) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

給出一個函數 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

代碼

/** // 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)* public int f(int x, int y);* };*/class Solution {public List<List<Integer>> findSolution(CustomFunction customfunction, int z) {List<List<Integer>> res=new ArrayList<>();for(int i=1;i<=z;i++)//嘗試不同的x{int l=1,r=z;while (l<=r)//二分查找符合的y{int mid=(r-l)/2+l;if(customfunction.f(i,mid)==z)//找到了結果{ArrayList<Integer> temp=new ArrayList<>();temp.add(i); temp.add(mid);res.add(temp);break;}else if(customfunction.f(i,mid)<z)l=mid+1;else r=mid-1;}}return res;} }

總結

以上是生活随笔為你收集整理的leetcode1237. 找出给定方程的正整数解(二分法)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。