EdwardZZZ / articles

工作点滴记录
2 stars 0 forks source link

面试题解答 #40

Open EdwardZZZ opened 6 years ago

EdwardZZZ commented 6 years ago

解绑匿名函数

const event = (function(){
    const handlers = {};
    return {
        on(el, type, fn, capture) {
            el.addEventListener(type, fn, !!capture);
            let fnKey = el.dataset['fnKey'];
            if (!fnKey) {
                el.dataset['fnKey'] = fnKey = type + (+new Date()).toString(36);
            }
            handlers[fnKey] = handlers[fnKey] || [];
            handlers[fnKey].push(fn);
        },
        off(el, type, fn) {
            if (fn) {
                el.removeEventListener(type, fn);
                return;
            }

            const fns = handlers[el.dataset['fnKey']];
            if (fns) {
                for (let n in fns) {
                    el.removeEventListener(type, fns[n]);
                };
            }
        }
    }
})();
EdwardZZZ commented 3 years ago

接雨水

const arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];

function trap(height) {
    const len = height.length;
    let [l, r, lMax, rMax, result] = [0, len - 1, 0, 0, 0];

    while (l < r) {
        const lh = heights[l];
        const rh = heights[r];

        if (lh < rh) {
            if (lh < lMax) {
                result += lMax - lh;
            } else {
                lMax = lh;
            }
            l++;
        } else {
            if (rh < rMax) {
                result += rMax - rh;
            } else {
                rMax = rh;
            }
            r--;
        }

        console.log(l, r);
    }

    return result;
};

console.log(trap(arr));
EdwardZZZ commented 3 years ago

滑动窗口中的最大值

const nums = [1, 3, -1, -3, 5, 3, 6, 7, 3, 3, 2, 2, 1, 1]

function maxSlidingWindow(nums, k) {
    const queue = [];
    const result = [];
    for (let i = 0; i < nums.length; i++) {
        // 如果新来的最大,清空队列
        if (nums[queue[0]] < nums[i]) queue.length = 0;

        // 清除失效
        if (queue.length > 0 && queue[0] < i - k + 1) queue.shift();

        // 清除中间,只留两头大的
        while(nums[queue[queue.length - 1]] < nums[i]) {
            queue.pop();
        }

        queue.push(i);

        if (i >= k - 1) result.push(nums[queue[0]]);
    }
    return result;
}

console.log(maxSlidingWindow(nums, 3));