旅行的形式为[旅行的起点,旅行的目的地]。您会以随机顺序获得行程。编写Javascript函数以找出旅程的起点。用户也可以输入参观的地方。
示例1:
exampleTrips:= [ [A,B], [B,C], [C,D] ]
此示例中的行程始于"A"
。
示例2:
exampleTrips:= [ [D,E], [F,D], [E,X] ]
此示例中的行程始于"F"
。
定义一个数组 将其拆分为两个数组a1和a2 找到b / w a1和a2之差 从a1返回剩余元素
var a = [ ['a', 'b'], ['b', 'c'], ['c', 'd'], ['e', 'a'] ];
var a1 = a.map(function(tuple) {
return tuple[0];
});
var a2 = a.map(function(tuple) {
return tuple[1];
});
function difference(a1, a2) {
var result = [];
for (var i = 0; i < a1.length; i++) {
if (a2.indexOf(a1[i]) === -1) {
result.push(a1[i]);
}
}
return result;
}
console.log(difference(a1, a2));
答案 0 :(得分:1)
首先,获取开始和结束(仅非重复元素),然后找出哪个是数组中的第一个元素:
const a = [['a','b'], ['b','c'],['d','a']];
const startEnd = a.reduce((acc, curr) => acc.concat(curr)).filter((e, i, arr) => arr.indexOf(e) == arr.lastIndexOf(e));
const res = a.findIndex(([e]) => startEnd.includes(e));
console.log(res);
答案 1 :(得分:0)
我有类似的面试问题,这是我的答案:
input {
udp {
type => "dhcp"
port => "518"
}
}
filter {
if [type] == "dhcp" {
grok {
match => {"message" => "assigned"}
}
}
}
output {
if [type] == "dhcp" and "_grokparsefailure" not in [tags] {
elasticsearch {
hosts => ["localhost:9200"]
index => "dhcp-%{+yyyy.MM.dd}-001"
}
}
}
答案 2 :(得分:0)
问题中的解决方案是O(n 2 )
您可以在O(n)中使用哈希图进行
const findStartingPoint = (trips) => {
// create a hash map of starting points from all trips
const tripStarts = trips.reduce((acc, trip) => {
acc[trip[0]] = false
return acc
}, {})
// get ending points from all trips
const tripEnds = trips.map(trip => trip[1])
tripEnds.forEach(end => {
tripStarts[end] = true
});
// get tripStarts - tripEnds
// I'm assuming a journey means continuous trips. This means Every start
// except for the journey start should be in trip ends
let start
Object.keys(tripStarts).forEach(tripKey => {
if(tripStarts[tripKey] === false) {
start = tripKey
}
})
return start ? start : 'You can start your trip anywhere'
}
console.log(findStartingPoint([['Cologne','Berlin'],['Munich','Cologne'],['YourPlace','Munich']]))
console.log(findStartingPoint(
[
['Cologne','Berlin'],
['Munich','Cologne'],
['YourPlace','Munich']
]) === 'YourPlace')
console.log(findStartingPoint(
[ ['A','B'], ['B','C'], ['C','D'] ]) === 'A')
console.log(findStartingPoint(
[ ['D','E'], ['F','D'], ['E','X'] ]) === 'F')
console.log(findStartingPoint(
[ ['A','B'], ['B','C'], ['C','D'], ['D', 'A']]) === 'You can start your trip anywhere')