Open zunsthy opened 5 days ago
、
需要一个堆
function li(i) { return (i << 1) + 1 }
function pi(i) { return (i - 1) >> 1 }
function Heap(arr = [], cmp = (a, b) => a < b) {
const h = []
const swap = (i, j) => {
[h[i], h[j]] = [h[j], h[i]]
}
const pop = () => {
swap(0, h.length - 1)
const top = h.pop()
let i = 0, c
while ((c = li(i)) < h.length) {
let j = c
if (c + 1 < h.length && cmp(h[c + 1], h[c]))
j = c + 1
if (cmp(h[i], h[j])) break;
swap(i, j)
i = j
}
return top
}
const push = (x) => {
let i = h.push(x) - 1
while (i) {
const p = pi(i)
if (cmp(h[p], h[i])) break
swap(p, i)
i = p
}
}
return {
_heap: h,
pop,
push,
get size() { return h.length },
get top() { return h[0] },
}
}
实现函数
function topK(arr, k) {
const h = Heap()
arr.forEach((e) => {
h.push(e)
if (h.size > k) h.pop()
})
return h.top
}
js 中无论是 object key 还是 map key,都具有后 set 即在最后的特性
function lru(n) {
const m = new Map
const limit = () => {
if (m.size > n)
m.delete(m.keys().next().value)
}
const get = (key) => m.get(key)
const set = (key, val) => {
if (m.has(key)) m.delete(key)
m.set(key, val)
limit()
}
return { get, set }
}
wec
一、
不能赢则返回 false
采用竖式乘法
随机一些数据,检查正确性
二、