leetcode每日一题(1237)
- 题意
- 思路:由于 f f f是单调递增函数,我们可以从 x = 1 , y = 1000 x = 1, y = 1000 x=1,y=1000开始,表示在横坐标为 [ x , 1000 ] [x, 1000] [x,1000]以及纵坐标为 [ 1 , y ] [1, y] [1,y]的举行范围内搜索答案。分类讨论:
- 如果 f ( x , y ) < z f(x, y) < z f(x,y)<z,那么对于任意的 y ′ < y y' < y y′<y,都有 f ( x , y ′ ) < f ( x , y ) < z f(x, y') < f(x, y) < z f(x,y′)<f(x,y)<z,这说明固定 x x x,无论怎样枚举 y y y,都无法找到答案,那么将 x x x加一,缩小搜索范围;
- 如果 f ( x , y ) > z f(x, y) > z f(x,y)>z,那对于任意 x ′ > x x' > x x′>x,都有 f ( x ′ , y ) > f ( x , y ) > z f(x', y) > f(x, y) > z f(x′,y)>f(x,y)>z,这说明固定 y y y枚举其余 x x x无法找到答案,那么将 y y y减一,缩小搜索范围;
- 如果 f ( x , y ) = z f(x, y) = z f(x,y)=z,那么记录答案,同情况1一样,将 x x x加一。由于 f ( x + 1 , y ) > f ( x , y ) = z f(x + 1, y) > f(x, y) = z f(x+1,y)>f(x,y)=z,根据情况2,可以同时将 y y y减一。
- 不断循环直到 x > 1000 x > 1000 x>1000或 y < 1 y < 1 y<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
- 分析
- 时间复杂度: O ( C ) , C < = 1000 O(C), C <= 1000 O(C),C<=1000;
- 空间复杂第: O ( 1 ) O(1) O(1)。