问题地址:https://leetcode.com/problems/evaluate-division/description/
题意:
给2个关系数组,给出一系列除法的结果,如果没有结果,返回-1 。
Given:a / b = 2.0, b / c = 3.0.
queries are:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return[6.0, 0.5, -1.0, 1.0, -1.0 ].
思路:
创建关系网,
a / b = 2.0 => a = b * 2.0 | b = a * 0.5 ,以此类推。
除此之外,还需要嵌套扩增关系网,
如果已有关系网中,a与b有关系,b与c有关系,c与d有关系,那关系网中必然还应该有:[a,c], [a,d], [b,d] 以上几个嵌套关系,具体代码如下:
/**
* @param {string[][]} equations
* @param {number[]} values
* @param {string[][]} queries
* @return {number[]}
*/
var calcEquation = function(equations, values, queries){
var results = [];
var relations = new Map();
function arrangeRelations(){
for (var i = 0; i < values.length; ++i){
if (equations[i][0] === equations[i][1])
continue;
var keyword = equations[i][0];
if (!relations.has(keyword)){
relations.set(keyword, []);
}
relations.get(keyword).push([values[i], equations[i][1]]);
keyword = equations[i][1];
if (!relations.has(keyword)){
relations.set(keyword, []);
}
relations.get(keyword).push([1 / values[i], equations[i][0]]);
}
enhanceRelations();
}
arrangeRelations();
function enhanceRelations() {
var addList = new Map();
relations.forEach((val1, key1) => {
for(let k = 0; k < val1.length; ++k) {
let key = val1[k][1];
if (relations.has(key)) {
for (let p = 0; p < relations.get(key).length; ++p) {
if (relations.get(key)[p][1] !== key1) {
if (!addList.has(key1)) {
addList.set(key1, new Set());
}
let vv = val1[k][0] * relations.get(key)[p][0];
let nn = relations.get(key)[p][1];
let contains = false;
for (let x of addList.get(key1)) {
if (x[1] === nn) {
contains = true;
break;
}
}
for (let x of relations.get(key1)) {
if (x[1] === nn) {
contains = true;
break;
}
}
if (!contains)
addList.get(key1).add([vv, nn]);
}
}
}
}
});
let length = 0;
addList.forEach((val, key) => {
if (!relations.has(key)) {
relations.set(key, [])
}
if (val.size) {
relations.set(key, relations.get(key).concat(Array.from(val)));
length ++;
}
});
debugger;
if (length) {
enhanceRelations();
}
}
for (var i = 0; i < queries.length; ++i) {
if (!relations.has(queries[i][0])) {
results.push(-1);
continue;
}
if (queries[i][0] === queries[i][1]) {
results.push(1);
continue;
}
var flag = false;
relations.forEach((val, key) => {
if (key === queries[i][0]) {
for(var k = 0;k < relations.get(key).length; ++k) {
var tmp = relations.get(key)[k];
if (tmp[1] === queries[i][1]) {
flag = true;
results.push(tmp[0]);
}
}
}
});
if (!flag)
results.push(-1);
}
return results;
};
calcEquation([["x1","x2"],["x2","x3"],["x3","x4"],["x4","x5"]],
[3.0,4.0,5.0,6.0],
[["x1","x5"],["x5","x2"],["x2","x4"],["x2","x2"],["x2","x9"],["x9","x9"]])
复制代码
Acceptd: