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
/* 根据传入参数n(数字)对一维数组(纯数字)按照距离n最近的顺序排序。(距离即数字与n的差值的绝对值) */ var arr = [7, 28, -1, 0, 7, 33]; function sort(n) { // your code }
The text was updated successfully, but these errors were encountered:
Sorry, something went wrong.
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));
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))
No branches or pull requests
The text was updated successfully, but these errors were encountered: