We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
//输入 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 }
验证下:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
一开始想的是先找出最小的from,然后无脑用from去硬匹配to就行,不过想了想总感觉不大对,比如有下面这种情况:
笨比了,根本不是要找最小的from,更类似于链表的形态,不存在to的from才是起点。还找个鸡儿最小from。
笨比解法开始:
验证下:
The text was updated successfully, but these errors were encountered: