Skip to content
New issue

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

from和to #56

Open
bibi7 opened this issue Dec 17, 2019 · 0 comments
Open

from和to #56

bibi7 opened this issue Dec 17, 2019 · 0 comments

Comments

@bibi7
Copy link
Owner

bibi7 commented Dec 17, 2019

//输入
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
}

验证下:
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant