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

编写一个程序将数组扁平化去并除其中重复部分数据,最终得到一个升序且不重复的数组 #19

Open
lvwxx opened this issue Aug 8, 2019 · 0 comments
Labels
arithmetic JavaScript commonly used algorithm question Further information is requested

Comments

@lvwxx
Copy link
Owner

lvwxx commented Aug 8, 2019

已知数组

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10]

解法一

function flat(arr) {
  return [...new Set(arr.flat(Infinity).sort((a,b) => a - b))]
}

解法二

function flat(arr) {
  return [...new Set(arr.toString().split(',').sort((a,b) => a-b))]
}

解法三(使用递归实现 flat 函数)

function flat(arr) {
  const flatArr = arr.reduce((res, next) => Array.isArray(next) ? res.concat(flat(next)) : res.concat(next),[])
  return [...new Set(flatArr.sort((a,b) => a - b))]
}

解法四(非递归实现 flat 函数)

// 使用 栈 来实现
// 由于栈后进先出的特点,先把原数组倒序
function flat(arr) {
  let stack = []
  let res = []

  for (let i = arr.length - 1; i >= 0; i--) {
    stack.push(arr[i])
  }

  while (stack.length) {
    const item = stack.pop()
    if (Array.isArray(item)) {
      for (let i = item.length - 1; i >= 0; i--) {
        stack.push(item[i])
      }
    } else {
      res.push(item)
    }
  }

  return [...new Set(res)].sort((a,b) => a - b)
}
@lvwxx lvwxx added question Further information is requested arithmetic JavaScript commonly used algorithm labels Aug 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
arithmetic JavaScript commonly used algorithm question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant