原题链接:
https://leetcode.cn/problems/find-positive-integer-solution-for-a-given-equation/
解题思路:
- 回顾题目给出的两个条件:
f(x, y) < f(x + 1, y)
f(x, y) > f(x, y - 1)
,由f(x, y) < f(x, y + 1)
变化而来
- 如果我们先声明
let x = 1, y = 1000
,相对于z
有以下几种情况:- 当
f(x, y) < z
时,只需要将x++
- 当
f(x, y) > z
时,只需要将y--
- 当
f(x, y) === z
时,当前x
和y
是一个解
- 当
- 当
x === 1000
且y === 1
时,所有的解都已经查找出来
/**
* @param {CustomFunction} customfunction
* @param {integer} z
* @return {integer[][]}
*/
var findSolution = function(customfunction, z) {
let result = [] // 存储结果
for (
// x默认值为左边界,y默认值为右边界
let x = 1, y = 1000;
// x向右移动,y向左移动,x和y都到达边界时,表示已经查找到所有结果,退出循环
x <= 1000 && y >= 1;
) {
// 计算当前x、y对应的结果
const subResult = customfunction.f(x, y)
// f(x, y) < f(x + 1, y)
if (subResult < z) {
x++
}
// f(x, y) > f(x, y - 1)
else if(subResult > z) {
y--
} else {
// f(x, y) === z,存储[x, y],并移动x和y
result.push([x++, y--])
}
}
return result
};
复杂度分析:
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( 1 ) O(1) O(1)。返回值不计入空间复杂度