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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

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

發布時間:2024/7/5 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 1237. 找出给定方程的正整数解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 題目

給出一個函數 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 位有符號整數。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/find-positive-integer-solution-for-a-given-equation
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。

2. 解題

類似題目:搜索二維矩陣
x=1,y=1,相當于矩陣左上角,x=1000,y=1000,相當于矩陣右下角

class Solution { public:vector<vector<int>> findSolution(CustomFunction& cf, int z) {int x = 1, y = 1000, val;vector<vector<int>> ans;while(x<=1000 && y >=1){val = cf.f(x,y);if(val < z)x++;else if(val > z)y--;else{ans.push_back({x,y});x++;}}return ans;} };

or

class Solution { public:vector<vector<int>> findSolution(CustomFunction& cf, int z) {int x = 1000, y = 1, val;vector<vector<int>> ans;while(x>=1 && y<=1000){val = cf.f(x,y);if(val < z)y++;else if(val > z)x--;else{ans.push_back({x,y});x--;}}return ans;} };

總結

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

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