zoukankan      html  css  js  c++  java
  • 前端基础之算法篇

    算法篇

    基础

    数组:数组支持高效的读和写操作,但是在插入和删除操作的时候性能很低
    链表:为了解决数组插入和删除低效的问题,出现了链表,但是链表的读操作性能很低
    栈:一种先入后出的数据结构,可以用数组或链表实现
    队列:一种先入先出的数据结构,可以用数组或链表实现
    优先队列:一种正常进,但是按照优先级出的数据结构
    树:树是一种有多个next节点的特殊的链表
    二叉树:二叉树是最多只有2个子节点的树
    二叉搜索树:左子树上的所有节点都小于右子树上的所有节点
    图:图是一种能够指回父节点的树
    

    代码模板

    // 递归
    function recursion(level, param1, param2, ...) {
        // terminator
        if (level > MAX_LEVEL) {
            return result;
        }
    
        // process data
        processData(level, data...)
    
        // drill down
        recursion(level + 1, p1, p2, ...)
    
        // other process if needed
        reverseState(level)
    }
    
    // 分治
    function divide(problem, param1, param2, ...) {
        // terminator
        if (problem === null) {
            return result;
        }
    
        // prepare data
        data = prepareData(problem);
        subProblems = splitProblem(problem, data);
    
        // process sub-problems
        subResult1 = divide(subProblems[0], p1, ...)
        subResult2 = divide(subProblems[1], p2, ...)
        subResult3 = divide(subProblems[2], p3, ...)
        ...
    
        // generate final result
        result = processResult(subResult1, subResult2, subResult3)
    }
    
    // bfs
    function bfs(tree) {
        const queue = [tree.root]
    
        while(queue.length > 0) {
            const node = queue.shift()
    
            // process node
            process(node)
    
            queue.push(node.children)
        }
    }
    
    // dfs
    function dfs(tree) {
        const stack = [tree.root]
    
        while(stack.length > 0) {
            const node = stack.pop()
    
            // process node
            process(node)
    
            stack.push(node.children)
        }
    }
    
    function dfsRecursion(tree) {
        // process node
        process(node)
    
        node.children.forEach(child => dfsRecursion(child))
    }
    
    // 二分
    function binarySearch(array, target) {
        const left = 0
        const right = array.length - 1
    
        while(left <= right) {
            const mid = (left + right) / 2
    
            if (array[mid] === target) {
                return mid
            } else if (array[mid] < target) {
                left = mid + 1
            } else {
                right = mid - 1
            }
        }
    }
    
  • 相关阅读:
    为初次使用linux设置 root密码
    linux如何改为汉化环境
    Linux 标准目录结构
    常用linux terminal 命令
    jquery 获取及设置input各种类型的值
    使用$.getJSON实现跨域ajax请求
    react 异步取数据
    PHP 全局变量
    PHP保存本地日志文件
    全端开发——css(选择器)
  • 原文地址:https://www.cnblogs.com/yangzhou33/p/13832998.html
Copyright © 2011-2022 走看看