算法学习记录(二十四)

91 阅读2分钟

问:

  1. 找到数组的每个数左边和右边比它大的最近的两个数,生成一个map结构返回
  2. 给定二叉树头节点,从节点a出发,可以向上或者向下,到达节点b时路过的节点数称为a到b的距离,求整个树的最大距离
  3. 给定一个无环多叉树头节点。假设每个节点都有number型的value。若选择当前节点,就不能再选择当前节点的子节点,如何取得value最大和。

解:

  1. 单调栈结构。
const findBigger = function (arr) {
    const stack = []
    const res = []
    for (let i of arr) {
        while (stack.length && stack[stack.length - 1] < i) {
            const item = stack.pop()
            res.push({
                left: stack[stack.length - 1],
                right: i,
                self: item
            })
        }
        stack.push(i)
    }
    while (stack.length) {
        const item = stack.pop()
        res.push({
            left: stack[stack.length - 1],
            right: undefined,
            self: item
        })
    }
    return res
}
  1. 递归树,返回两个信息,树的深度和这棵树的最大距离。取到左右树信息后,得到当前树的深度和,当前树的最大距离取左右子树的最大距离和当前树深度和中的最大值。
function getMaxDis(root) {
    function getRes(node) {
        // 递归到底部时,返回深度0,最大距离0
        if (!node) return {
            deep: 0,
            distance: 0
        }
        let leftInfo = getRes(node.left)
        let rightInfo = getRes(node.right)
        // 当前树的深度和,就是左右子树深度相加再 + 1
        const deep = leftInfo.deep + rightInfo.deep + 1
        // 取三者最大值
        const distance = Math.max(deep, Math.max(leftInfo.distance, rightInfo.distance))
        return {
            deep,
            distance
        }
    }
    const { deep, distance } = getRes(root)
    return Math.max(deep, distance)
}
  1. 把每个节点分为选、不选两种情况。
function getMaxValues(root) {
    function getRes(node) {
        // 当没有子节点时
        if (!node.children.length) return {
            noSelect: 0,
            select: node.value
        }
        // 选当前节点时的最大收益
        let select = node.value
        // 不选当前节点时的最大收益
        let noSelect = 0
        for (let i = 0; i < node.children.length; i++) {
            const itemInfo = getRes(node.children[i])
            // 选当前节点的情况,就是当前value再加上每一个子节点不选的情况
            select += itemInfo.noSelect
            // 不选当前节点的情况,可以选择是否选子节点。那么选更大的情况
            noSelect += Math.max(itemInfo.select, itemInfo.noSelect)
        }
        return {
            select,
            noSelect
        }
    }
    const { select, noSelect } = getRes(root)
    return Math.max(select, noSelect)
}