leetcode每日一題(1237找出給定方程的正整數(shù)解)

  1. 題意
  2. 思路:由于f是單調(diào)遞增函數(shù),我們可以從x = 1, y = 1000開(kāi)始,表示在橫坐標(biāo)為[x, 1000]以及縱坐標(biāo)為[1, y]的舉行范圍內(nèi)搜索答案。分類討論:
  • 如果f(x, y) < z,那么對(duì)于任意的y' < y,都有f(x, y') < f(x, y) < z,這說(shuō)明固定x,無(wú)論怎樣枚舉y,都無(wú)法找到答案,那么將x加一,縮小搜索范圍;
  • 如果f(x, y) > z,那對(duì)于任意x' > x,都有f(x', y) > f(x, y) > z,這說(shuō)明固定y枚舉其余x無(wú)法找到答案,那么將y減一,縮小搜索范圍;
  • 如果f(x, y) = z,那么記錄答案,同情況1一樣,將x加一。由于f(x + 1, y) > f(x, y) = z,根據(jù)情況2,可以同時(shí)將y減一。
  • 不斷循環(huán)直到x > 1000y < 1為止,此時(shí)搜索范圍為空。
  1. 代碼:
    C++代碼:
/*
 * // 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& f, int z) {
        vector<vector<int>> res;
        int i = 1, j = 1000;
        while(i <= 1000 && j >= 1) {
            if (f.f(i, j) == z) res.push_back({i ++, j --});
            if (f.f(i, j) > z) --j;
            if (f.f(i, j) < z) ++i;
        }
        return res;

        
    }
};

Python代碼

"""
   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)
       def f(self, x, y):
  
"""
class Solution:
    def findSolution(self, customfunction: 'f', z: int) -> List[List[int]]:
        res = []
        i, j = 1, 1000
        while(i <=1000 and j >= 1):
            if customfunction.f(i, j) == z:
                res.append([i, j])
                i += 1
                j += 1
            if customfunction.f(i, j) < z:   i += 1
            if customfunction.f(i, j) > z:   j -= 1
        return res
  1. 分析
  • 時(shí)間復(fù)雜度:O(C), C <= 1000;
  • 空間復(fù)雜第:O(1)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容