Open chencl1986 opened 2 months ago
原题链接: 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 };
复杂度分析:
原题链接: 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
时,所有的解都已经查找出来复杂度分析: