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