使用数组的目标城市



我有随机的飞行路径,这些阵列可以是有序的,也可以是无序的,我的目标是找到目的地城市。

我的输入是paths = [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]

我想要的输出是";圣保罗";我的第一个嵌套for循环是检查航班是否有起点和终点(因为圣保罗没有终点(

我当前的代码如下:

var destCity = function(paths) { 
let truePath = [];
let  answer = "";

// finds verified paths first two for loops are to find and compare all trips  starting and and a stopping points and the if statment is there to take the trips that have a starting and stopping point that corispond to another flight and log them into a new array called truePath
for (let i = 0; i < paths.length; i++) {
for (let j = 0; j< paths[i].length; j++) {
if (paths[i][1] == paths[j][0]) {
truePath.push(paths[i][1]);
//should return [New York, Lima] but only returns [New York]
return truePath;
}
}
}

//tests for destination using verified paths, these for loops are for comparing the truePath array with the final desination of each flight. if the truePath array containes the starting desination of the final desination then then the answer = the final desination   
for (let k = 0; k < paths.length; k++) {
for (let l = 0; l < paths.length; l++) {
if (truePath[k] == paths[l][0]) {
answer = paths[l][1].toString();
break;
}
}
}

};

当我返回我的truePath/我已验证的路径时,我只得到[纽约]。我如何才能让它返回[纽约、利马]或任何有起点和终点的路径?

您需要找到一个目的地城市,该城市不在任何数组的原点位置。

因此,创建一个包含所有起源城市的Set。然后findpaths中的数组,其目的地不在原点集中。

const paths = [["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]],
origins = new Set(paths.map(p => p[0])),
output = paths.find(p => !origins.has(p[1]))[1]
console.log(output)

您可以使用两个循环,一个用于将值添加到哈希中,另一个用于查找未绑定的正值。

function findDestination(paths) {
const cities = {};

for (const [departure, arrival] of paths) {
cities[departure] = (cities[departure] || 0) - 1;
cities[arrival] = (cities[arrival] || 0) + 1;
}
return Object.keys(cities).find(city => cities[city] === 1);
}
console.log(findDestination([["London", "New York"], ["New York", "Lima"], ["Lima", "Sao Paulo"]]));

最新更新