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

按要求实现代码 #821

Open
lgwebdream opened this issue Jul 6, 2020 · 3 comments
Open

按要求实现代码 #821

lgwebdream opened this issue Jul 6, 2020 · 3 comments
Labels
算法 teach_tag 高思教育 company

Comments

@lgwebdream
Copy link
Owner

/* 
  根据传入参数n(数字)对一维数组(纯数字)按照距离n最近的顺序排序。(距离即数字与n的差值的绝对值)
*/
var arr = [7, 28, -1, 0, 7, 33];
function sort(n) {
  // your code
}
@lgwebdream lgwebdream added 算法 teach_tag 高思教育 company labels Jul 6, 2020
@lgwebdream
Copy link
Owner Author

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

@AAA611
Copy link

AAA611 commented Aug 31, 2022

var arr = [7, 28, -1, 0, 7, 33];
function sort(n) {
  const sortedArr = arr.sort((a, b) => a - b)
  const index = arr.indexOf(n)
  let left = index - 1
  let right = index + 1
  let res = [n]
  while (left >= 0 && right < arr.length) {
    if ((n - sortedArr[left]) < (sortedArr[right] - n)) {
      res.push(sortedArr[left])
      left--
    } else if ((n - sortedArr[left]) > (sortedArr[right] - n)) {
      res.push(sortedArr[right])
      right++
    } else {
      res.push(sortedArr[left], sortedArr[right])
      left--
      right++
    }
  }
  if (left >= 0) {
    res.push(...sortedArr.slice(0, left + 1))
  }
  if (right < arr.length) {
    res.push(...sortedArr.slice(right))
  }
  return res
}
console.log(sort(7));

@DaphnisLi
Copy link

const sort = (arr, n) => {
  const obj = []
  for (const value of arr) {
    obj.push(
      {
        value,
        gap: Math.abs(value - n),
      },
    )
  }
  obj.sort((a, b) => a.gap - b.gap)
  return obj.map(item => item.value)
}

console.log(sort([7, 28, -1, 0, 7, 33], 7))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 teach_tag 高思教育 company
Projects
None yet
Development

No branches or pull requests

3 participants