LeetCode 1237. 找出给定方程的正整数解
生活随笔
收集整理的這篇文章主要介紹了
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,相當于矩陣右下角
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. 找出给定方程的正整数解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 887. 鸡蛋掉落(D
- 下一篇: LeetCode 1145. 二叉树着色