算法学习记录(五十六)

77 阅读1分钟

目前视频学习告一段落,先开始刷剑指offer系列

问:

  1. 剑指 Offer 03. 数组中重复的数字
  2. 剑指 Offer 04. 二维数组中的查找
  3. 剑指 Offer 05. 替换空格
  4. 剑指 Offer 06. 从尾到头打印链表
  5. 剑指 Offer 07. 重建二叉树
  6. 剑指 Offer 09. 用两个栈实现队列
  7. 剑指 Offer 10- I. 斐波那契数列 解:
const findRepeatNumber = function(nums) {
    const hashMap = new Map()
    for (let i of nums) {
        if (hashMap.get(i)) return i
        hashMap.set(i, 1)
    }
    return null
};
const findNumberIn2DArray = function(matrix, target) {
    if (!matrix.length) return false
    let x = 0
    let y = matrix[0].length - 1
    while(x < matrix.length && y >=0) {
        const cur = matrix[x][y]
        if (cur > target) {
            y--
        }
        if (cur < target) {
            x++
        }
        if (cur === target ) {
            return true
        }
    }
    return false
};
const replaceSpace = function(s) {
    const newArr = s.split(' ')
    return newArr.join('%20')
};
const reversePrint = function(head) {
    let curNode = head
    const res = []
    while (curNode) {
        res.unshift(curNode.val)
        curNode = curNode.next
    }
    return res
};
const buildTree = function(preorder, inorder) {
    function getRes(a1, a2) {
        if (!a1.length) return null
        const mid = a1[0]
        const node = new TreeNode(mid)
        const idx = a2.findIndex(item => item === mid)
        const leftA2 = a2.slice(0, idx)
        const leftA1 = a1.slice(1, 1 + leftA2.length)
        const rightA2 = a2.slice(idx + 1)
        const rightA1 = a1.slice(1 + leftA2.length, 1 + rightA2.length + leftA2.length)
        node.left = getRes(leftA1, leftA2)
        node.right = getRes(rightA1, rightA2)
        return node
    }
    return getRes(preorder, inorder)
};
const CQueue = function() {
    this.stack1 = []
    this.stack2 = []
};

CQueue.prototype.appendTail = function(value) {
    this.stack1.push(value)
};

CQueue.prototype.deleteHead = function() {
    if (this.stack2.length) return this.stack2.pop()
    while(this.stack1.length) {
        this.stack2.push(this.stack1.pop())
    }
    return this.stack2.pop() ?? -1
};
const fib = function(n) {
    const MOD = 1000000007;
    const dp = []
    dp[0] = 0
    dp[1] = 1
    for (let i = 2; i <= n; ++i) {
        dp[i] = (dp[i - 1] + dp[i - 2]) % MOD
    }
    return dp[n] 
};