Open bibi7 opened 4 years ago
//输入 const array = [ {from:4, to:5}, {from:3, to:4}, {from:10, to:6}, {from:5, to:10}, {from:6, to:7} ] //输出 //[{from:3, to:4}, {from:4, to:5}, {from:5, to:10}, {from:10, to:6}, {from:6, to:7}]
一开始想的是先找出最小的from,然后无脑用from去硬匹配to就行,不过想了想总感觉不大对,比如有下面这种情况:
//输入 const array = [ {from:4, to:5}, {from:18, to:4}, {from:10, to:6}, {from:5, to:10}, {from:6, to:7} ] //输出 //[{from:18, to:4}, {from:4, to:5}, {from:5, to:10}, {from:10, to:6}, {from:6, to:7}]
笨比了,根本不是要找最小的from,更类似于链表的形态,不存在to的from才是起点。还找个鸡儿最小from。
function sortArray(array) { const fromArray = []; const toArray = []; for (let i = 0; i < array.length; i++) { const item = array[i]; fromArray.push(item.from) toArray.push(item.to) } const resultFirstIndex= fromArray.find(item => toArray.indexOf(item) === -1) const resultFirstObj = array.find(item => item.from === resultFirstIndex) const result = [] result.push(resultFirstObj) while (result.length < array.length) { result.push(array.find(item => item.from === result[result.length - 1]['to'])) } return result }
验证下:
一开始想的是先找出最小的from,然后无脑用from去硬匹配to就行,不过想了想总感觉不大对,比如有下面这种情况:
笨比了,根本不是要找最小的from,更类似于链表的形态,不存在to的from才是起点。还找个鸡儿最小from。
笨比解法开始:
验证下: