forked from lessfish/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection.js
More file actions
44 lines (40 loc) · 1001 Bytes
/
Copy pathcollection.js
File metadata and controls
44 lines (40 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/****** 典型的算法案例收集 ******/
const arr = [
['B', 'C'],
['A', 'D'],
['D', 'B'],
['X', 'Y'],
];
/**
* 获取接龙长度的算法
* 接收二维数组作为参数
* 二维数组内元素分头尾,且不重复,也不会形成环
* 使用 Map, 在循环内使用循环
* @param arr
* @returns
*/
function getChain(arr) {
let map = new Map();
let res = [];
// 先保存一份所有的键值对
for (let i = 0; i < arr.length; i++) {
const [key, value] = arr[i];
map.set(key, value);
}
for (let i = 0; i < arr.length; i++) {
const [key] = arr[i];
let first = key;
let current = [];
while (first) {
current.push(first);
// 键值对索引的方式来指向下一个,如果有就继续接龙,没有则停止
first = map.get(first);
}
// 如果拿到更长的接龙,则保存新的接龙
if (current.length > res.length) {
res = current;
}
}
console.info(res);
return res.length;
}