1.除法求值
题目:
给出方程式 A / B = k, 其中 A 和 B 均为用字符串表示的变量, k 是一个浮点型数字。根据已知方程式求解问题,并返回计算结果。如果结果不存在,则返回 -1.0。
输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。
思路:类似线段树。首先明确,a/b=1/(b/a),所以,用map记录每一种计算结果,并延伸处理。
对于已知的a/b,首先记录a-->b和b-->a,然后,如果对a的key遍历(除key为b),假设此时已知a-->c,那么也要计算c-->b,并记录c-->b和b-->c
时间复杂度O(n2),空间复杂度O(n2)
/**
* @param {string[][]} equations
* @param {number[]} values
* @param {string[][]} queries
* @return {number[]}
*/
var calcEquation = function(equations, values, queries) {
const map = {};
const l = equations.length;
for (let i = 0; i < l; i++) {
const [a, b] = equations[i];
dfs(values[i], a, b);
dfs(1 / values[i], b, a);
}
function dfs(v, a, b) {
if (map[a]) {
if (map[a][b] === undefined) {
map[a][b] = v;
}
const keys = Object.keys(map[a]);
keys.forEach((item) => {
if (item == b) return;
if (map[item][b] !== undefined) return;
const tempv = map[a][item];
dfs(v / tempv, item, b);
dfs(tempv / v, b, item);
});
} else {
map[a] = {
[b]: v,
};
}
}
function getV(a, b) {
if (!map[a] || !map[b]) return -1;
if (a === b) return 1;
if (map[a][b] === undefined && map[b][a] === undefined) return -1;
return map[a][b] === undefined ? map[b][a] : map[a][b];
}
return queries.map((item) => getV(item[0], item[1]));
};
2.第N个数字
题目:
在无限的整数序列 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...中找到第 n 个数字。