Last active
June 20, 2019 13:38
-
-
Save YiqinZhao/74aa78996741637ae3567282d6f21692 to your computer and use it in GitHub Desktop.
[yuanfudao-interview] 猿辅导前端面试总结 #interview
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let N = 10 | |
let source = [] | |
let M = 4 | |
for (let i = 0; i < N; i++) { | |
let len = Math.floor(Math.random() * 5) + 5 | |
let item = [] | |
for (let j = 0; j < len; j++) item.push(Math.floor(Math.random() * 10)) | |
source.push(item) | |
} | |
// 1. n 个数组,取其中第M大的数 | |
// Your Code Here | |
let res = source.reduce((arr, v) => arr.concat(v), []) | |
.sort() | |
.reverse() | |
if (M < 0 || M > res.length - 1) { | |
console.error('Exceeded') | |
} else { | |
console.log(res[M - 1]) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let tree = { | |
value: 1, | |
left: { | |
value: 2, | |
left: { | |
value: 4, | |
left: null, | |
right: null | |
}, | |
right: { | |
value: 5, | |
left: null, | |
right: null | |
} | |
}, | |
right: { | |
value: 3, | |
left: { | |
value: 6, | |
left: null, | |
right: null | |
}, | |
right: { | |
value: 7, | |
left: null, | |
right: null | |
} | |
} | |
} | |
// 按行输出二叉树 | |
let queue = [tree] | |
function generate() { | |
if (queue.length === 0) return | |
let item = queue.shift() | |
console.log(item.value) | |
if (item.left) { queue.push(item.left) } | |
if (item.right) { queue.push(item.right) } | |
generate() | |
} | |
generate() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9] | |
// Shuffle, 打乱一个数组 | |
// 方法一,并非真正的 shuffle | |
console.log(arr.sort((a, b) => Math.random() - .5)) | |
// 方法二,Fisher–Yates shuffle | |
let i = arr.length - 1 | |
while (i > 0) { | |
let p = Math.floor(Math.random() * (i - 1)) | |
let tmp = arr[i] | |
arr[i] = arr[p] | |
arr[p] = tmp | |
i-- | |
} | |
console.log(arr) |
q3那个应该是
console.log(arr.sort((a, b) => Math.random() - .5))
吧
感谢指正,Array.prototype.sort()
方法接受的闭包函数式按照返回值与0
的关系来进行排序的,这一点之前写的时候记错了。ref: MDN
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
q3那个应该是
吧