数据结构学习记录

数据结构

数组 & 链表
相连性 | 指向性
数组可以迅速定位到数组中某一个节点的位置
链表则需要通过前一个元素指向下一个元素,需要前后依赖顺序查找,效率较低

实现链表

//    head => node1 => node2 => ... => null

class Node {
    constructor(element) {
        this.element = element;
        this.next = null;
    }
}


class LinkList {
    constructor() {
        this.length = 0;
        //    1.空链表特征 => 判断链表的长度
        this.head = null;
    }
    
    //    返回索引对应的元素
    getElementAt(position) {
        //    边缘检测
        if (position < 0 || position >= this.length) {
            return null;
        }
        
        let _current = this.head;
        for (let i = 0; i < position; i++) {
            _current = _current.next;
        }
        
        return _current;
    }
    
    //    查找元素所在位置
    indexOf(element) {
        let _current = this.head;
        for (let i = 0; i < this.length; i++) {
            if (_current === element) return i;
            _current = _current.next;
        }
        return -1;
    }
    
    //    添加节点 在尾部加入
    append(element) {
        _node = new Node(element);
        
        if (this.head === null) {
            this.head = _node;
        } else {
            this.getElementAt(this.length - 1);
            _current.next = _node;
        }
        this.length++;   
    }
    
    //    插入节点    在中间插入
    insert(position, element) {
        if (position < 0 || position > this.length) return false;
        
        let _node = new Node(element);
        if (position === 0) {
            _node.next = this.head;
            this.head = _node;
        } else {
            let _previos = this.getElementAt(position - 1);
            _node.next = _previos;
            _previos.next = _node;
        }
        this.length++;
        return true;
    }
    
    //    删除指定位置元素
    removeAt(position) {
        if (position < 0 || position > this.length) return false;
        
        if (position === 0) {
            this.head = this.head.next;
        } else {
            _previos = this.getElementAt(position - 1);
            let _current = _previos.next;
            _previos.next = current.next;            
        }
        this.length--;
        return true;
    }
    
    //    删除指定元素
    remove(element) {
    }
}

特点:先入后出(薯片桶)

队列

特点:先入先出(排队)

哈希

特点:快速匹配定位

遍历 前序遍历(中左右) 中序遍历(左中右) 后序遍历(左右中)
1.二叉树 or 多子树
2.结构定义
a.树是非线性结构
b.每个节点都有0个或多个后代

面试真题:

判断括号是否有效自闭合

算法流程:
1.确定需要什么样的数据结构,满足模型的数据 - 构造变量 & 常量
2.运行方式 简单条件执行 | 遍历 | 递归 - 算法主体结构
3.确定输入输出 - 确定流程

    //    '{}[]' 和 '[{}]' true,   
    //    '{{}[]' false
const stack = [];

const brocketMap = {
    '{': '}',
    '[': ']',
    '(': ')'
};

let str = '{}';

function isClose(str) {
    for (let i = 0; i < str.length; i++) {
        const it = str[i];
        if (!stack.length) {
            stack.push(it);
        } else {
            const last = stack.at(-1);
            if (it === brocketMap[last]) {
                stack.pop();
            } else {
                stack.push(it);
            }
        }
    }
    
    if (!stack.length) return true;

    return false;
}

isClose(str);

遍历二叉树

//    前序遍历
class Node {
    constructor(node) {
        this.left = node.left;
        this.right = node.right;
        this.value = node.value;
    }
}
//    前序遍历
const PreOrder = function(node) {
    if (node !== null) {
        console.log(node.value);
        PreOrder(node.left);
        PreOrder(node.right);
    }
}
//    中序遍历
const InOrder = function(node) {
    if (node !== null) {
        InOrder(node.left);
        console.log(node.value);
        InOrder(node.right);
    }
}
//    后序遍历
const PostOrder = function(node) {
    if (node !== null) {
        PostOrder(node.left);
        PostOrder(node.right);
        console.log(node.value);
    }
}

树结构深度遍历

const tree = {
    value: 1,
    children: [
        {
            value: 2,
            children: [
                { value: 3 },
                {
                    value: 4, children: [
                        { value: 5 }
                    ]
                }
            ]
        },
        { value: 5 },
        {
            value: 6, 
            children: [
                { value: 7 }
            ]
        }
    ]
}
//    优先遍历节点的子节点 => 兄弟节点
//    递归方式
function dfs(node) {
    console.log(node.value);
    if (node.children) {
        node.children.forEach(child => {
            dfs(child);
        })   
    }
}

//    遍历 - 栈
function dfs() {
    const stack = [node];
    while (stack.length > 0) {
        const current = stack.pop();
        console.log(current.value);
        if (current.children) {
            const list = current.children.reverse();
            stack.push(...list);
        }
    }
 }

树结构广度优先遍历

const tree = {
    value: 1,
    children: [
        {
            value: 2,
            children: [
                { value: 3 },
                {
                    value: 4, children: [
                        { value: 5 }
                    ]
                }
            ]
        },
        { value: 5 },
        {
            value: 6, 
            children: [
                { value: 7 }
            ]
        }
    ]
}

//    1. 递归
function bfs(nodes) {
    const list = []
    nodes.forEach(child => {
        console.log(child.value);
        if (child.children && child.children.length) {
            list.push(...child.children);
        }
    })
    if (list.length) {
        bfs(list);    
    }
}
bfs([tree]);

//    1.递归 - 方法2
function bfs(node, queue = [node]) {
    if (!queue.length) return;
    
    const current = queue.shift();
    if (current.children) {
        queue.push(...current.children);
    }
    
    bfs(null, queue);
}
bfs(tree);


//    2. 递归
function bfs(node) {
    const queue = [node];
    while(queue.length > 0) {
        const current = queue.shift();
        if (current.children) {
            queue.push(...current.children);
        }
    }
}

实现快速构造一个二叉树

1.若他的左子树非空,那么他的所有左子节点的值应该小于根节点的值
2.若他的右子树非空,那么他的所有右子节点的值应该大于根节点的值
3.他的左 / 右子树 各自又是一颗满足下面两个条件的二叉树

class Node {
    constructor(key) {
        this.key = key
        this.left = null;
        this.right = null;
    }
}

class BinaryTree {
    constructor() {
    //    根节点
        this.root = null;
    }
    
    //    新增节点
    insert(key) {
        const newNode = new Node(key);
        
        const insertNode = (node, newNode) => {
            if (newNode.key < node.key) {
    //    没有左节点的场景 => 成为左节点
                node.left ||= newNode;
                
    //    已有左节点的场景 => 递归改变参照物,与左节点进行对比判断插入位置
                inertNode(node.left, newNode);
            } else {
    //    没有左节点的场景 => 成为左节点
                node.right ||= newNode;
                
    //    已有左节点的场景 => 递归改变参照物,与左节点进行对比判断插入位置
                inertNode(node.right, newNode);
            }
        }
        
        this.root ||= newNode;
        //    有参照物后进去插入节点
        insertNode(this.root, newNode);
    }
    
    //    查找节点
    contains(node) {        
        const searchNode = (referNode, currentNode) => {
            if (currentNode.key === referNode.key) {
                return true;
            }
            if (currentNode.key > referNode.key) {
                 return searchNode(referNode.right, currentNode);
            }
            
            if (currentNode.key < referNode.key) {
                 return searchNode(referNode.left, currentNode);
            }
            
            return false;
        }
        return searchNode(this.root, node);
    }
    
    //    查找最大值
    findMax() {
        let max = null;
        
        //    深度优先遍历
        const dfs = node => {
            if (node === null) return;
            if (max === null || node.key > max) {
                max = node.key;
            }
            dfs(node.left);
            dfs(node.right);
        }
        
        dfs(this.root);
        return max;
    }
    
    //    查找最小值
    findMin() {
        let min = null;
        
        //    深度优先遍历
        const dfs = node => {
            if (node === null) return;
            if (min === null || node.key < min) {
                min = node.key;
            }
            dfs(node.left);
            dfs(node.right);
        }
        
        dfs(this.root);
        return min;
    }
    
    //    删除节点
    remove(node) {
        const removeNode = (referNode, current) => {
            if (referNode.key === current.key) {
                if (!node.left && !node.right) return null;
                if (!node.left) return node.right;
                if (!node.right) return node.left;
                
            }
        }
        
        return removeNode(this.root, node);
    }
}

平衡二叉树

在这里插入图片描述

class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
        this.height = 1;
    }
}


class AVL {
    constructor() {
        this.root = null;
    }
    
    // 插入节点
    insert(key, node = this.root) {
    	if (node === null) {
    		this.root = new Node(key);
    		return;
    	}
    
    	if (key < node.key) {
    		node.left = this.insert(key, node.left);
    	} else if (key > node.key) {
    		node.right = this.insert(key, node.right);
    	} else {
    		return;
    	}
    
    	// 平衡调整
    	const balanceFactor = this.getBalanceFactor(node);
    	if (balanceFactor > 1) {
    		if (key < node.left.key) {
    			node = this.rotateRight(node);
    		} else {
    			node.left = this.rotateLeft(node.left);
    			node = this.rotateRight(node);
    		}
    	} else if (balanceFactor < -1) {
    		if (key > node.right.key) {
    			node = this.rotateLeft(node);
    		} else {
    			node.right = this.rotateRight(node.right);
    			node = this.rotateLeft(node);
    		}
    	}
    
    	this.updateHeight(node);
    	return node;
    }
    
    // 获取节点平衡因子
    getBalanceFactor(node) {
        return this.getHeight(node.left) - this.getHeight(node.right);
    }
    
    rotateLeft(node) {      
        const newRoot = node.right;        
        node.right = newRoot.left;        
        newRoot.left = node;
        
        //    这里是为了校准更新的这两个节点的高度。只需要把他的左右节点的高度拿来 加1即可
        node.height = Math.max(
            this.getHeight(node.left),
            this.getHeight(node.right)
        ) + 1;
        newRoot.height = Math.max(
            this.getHeight(newRoot.left),
            this.getHeight(newRoot.right)
        ) + 1;

        return newRoot;
    }
    
    getHeight(node) {
        if (!node) return 0;
        return node.height;
    }
}

红黑树

参考写法

let RedBlackTree = (function() {
    let Colors = {
        RED: 0,
        BLACK: 1
    };

    class Node {
        constructor(key, color) {
            this.key = key;
            this.left = null;
            this.right = null;
            this.color = color;

            this.flipColor = function() {
                if(this.color === Colors.RED) {
                    this.color = Colors.BLACK;
                } else {
                    this.color = Colors.RED;
                }
            };
        }
    }

    class RedBlackTree {
        constructor() {
            this.root = null;
        }

        getRoot() {
            return this.root;
        }

        isRed(node) {
            if(!node) {
                return false;
            }
            return node.color === Colors.RED;
        }

        flipColors(node) {
            node.left.flipColor();
            node.right.flipColor();
        }

        rotateLeft(node) {
            var temp = node.right;
            if(temp !== null) {
                node.right = temp.left;
                temp.left = node;
                temp.color = node.color;
                node.color = Colors.RED;
            }
            return temp;
        }

        rotateRight(node) {
            var temp = node.left;
            if(temp !== null) {
                node.left = temp.right;
                temp.right = node;
                temp.color = node.color;
                node.color = Colors.RED;
            }
            return temp;
        }

        insertNode(node, element) {

            if(node === null) {
                return new Node(element, Colors.RED);
            }

            var newRoot = node;

            if(element < node.key) {

                node.left = this.insertNode(node.left, element);

            } else if(element > node.key) {

                node.right =this.insertNode(node.right, element);

            } else {
                node.key = element;
            }

            if(this.isRed(node.right) && !this.isRed(node.left)) {
                newRoot = this.rotateLeft(node);
            }

            if(this.isRed(node.left) && this.isRed(node.left.left)) {
                newRoot = this.rotateRight(node);
            }
            if(this.isRed(node.left) && this.isRed(node.right)) {
                this.flipColors(node);
            }

            return newRoot;
        }

        insert(element) {
            this.root = insertNode(this.root, element);
            this.root.color = Colors.BLACK;
        }
    }
    return RedBlackTree;
})()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/560145.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

AI原生时代,操作系统为何是创新之源?

一直以来&#xff0c;操作系统都是软件行业皇冠上的明珠。 从上世纪40、50年代&#xff0c;汇编语言和汇编器实现软件管理硬件&#xff0c;操作系统的雏形出现&#xff1b;到60年代&#xff0c;高级编程语言和编译器诞生&#xff0c;开发者通过操作系统用更接近人的表达方式去…

面向对象(一)

一.类与对象的定义 (1)类(设计图):是对象共同特征的描述: (2)对象:是真实存在的具体东西。 在Java中,必须先设计类&#xff0c;才能获取对象。 二.如何定义类 public class 类名{1.成员变量(代表属性,一般是名词) 2.成员方法(代表行为,一般是动词) 3.构造器 4.代码块 5.内部…

Liunx入门学习 之 基础操作指令讲解(小白必看)

股票的规律找到了&#xff0c;不是涨就是跌 一、Linux下基本指令 1.ls 指令 2.pwd 命令 3.cd 指令 4.touch 指令 5.mkdir 指令 6.rmdir指令 && rm 指令 7.man 指令 8.cp 指令 9.mv指令 10.cat 11.more 指令 12.less 指令 13.head 指令 14.tail 指令 15…

论文解读-Contiguitas: The Pursuit of Physical Memory Contiguity in Datacenters

研究背景&#xff1a; 在内存容量飞速增长的背景下&#xff0c;使用小页管理内存会带来巨大的内存管理开销&#xff08;地址转换开销高&#xff09;。近些年来不少研究尝试给应用分配大段连续区域&#xff0c;或者改善页表结构&#xff08;如使用hash结构的页表&#xff09;以降…

质谱原理与仪器2-笔记

质谱原理与仪器2-笔记 常见电离源电子轰击电离源(EI)碎片峰的产生典型的EI质谱图 化学电离源(CI)快原子轰击源(FAB)基体辅助激光解析电离(MALDI)典型的MALDI质谱图 大气压电离源(API)电喷雾离子源(ESI)大气压化学电离源(APCI)APCI的正负离子模式 大气压光电离源(APPI) 常见电离…

玄子Share-计算机网络参考模型

玄子Share-计算机网络参考模型 分层思想 利用七层参考模型&#xff0c;便于在网络通信过程中&#xff0c;快速的分析问题&#xff0c;定位问题并解决问题 将复杂的流程分解为几个功能相对单一的子过程 整个流程更加清晰&#xff0c;复杂问题简单化 更容易发现问题并针对性的…

线上频繁fullgc问题-SpringActuator的坑

整体复盘 一个不算普通的周五中午&#xff0c;同事收到了大量了cpu异常的报警。根据报警表现和通过arthas查看&#xff0c;很明显的问题就是内存不足&#xff0c;疯狂无效gc。而且结合arthas和gc日志查看&#xff0c;老年代打满了&#xff0c;gc不了一点。既然问题是内存问题&…

Python练习03

题目 解题思路 Demo58 通过字符串切片来进行反转操作 def _reverse():"""这是一个反转整数的函数"""num input("请输入想要反转的整数")print(num[::-1]) 运行结果 Demo61 首先制作一个判断边长的函数&#xff0c;通过三角形两边…

又成长了,异常掉电踩到了MySQL主从同步的坑!

&#x1f4e2;&#x1f4e2;&#x1f4e2;&#x1f4e3;&#x1f4e3;&#x1f4e3; 哈喽&#xff01;大家好&#xff0c;我是【IT邦德】&#xff0c;江湖人称jeames007&#xff0c;10余年DBA及大数据工作经验 一位上进心十足的【大数据领域博主】&#xff01;&#x1f61c;&am…

Google Earth Engine 洪水制图 - 使用 Sentinel-1 SAR GRD

Sentinel-1 提供从具有双极化功能的 C 波段合成孔径雷达 (SAR) 设备获得的信息。该数据包括地面范围检测 (GRD) 场景,这些场景已通过 Sentinel-1 工具箱进行处理,以创建经过校准和正射校正的产品。该集合每天都会更新,新获得的资产会在可用后两天内添加。 该集合包含所有 G…

《王者荣耀》Hello Kitty 小兵皮肤完整设置指南

王者荣耀与三丽鸥的联动活动上线了 Hello Kitty 小兵皮肤&#xff0c;让我们的峡谷小兵们也能穿上漂亮的衣服啦&#xff01;这款皮肤极具卡哇伊风格&#xff0c;引起了许多玩家的关注。许多小伙伴都想知道如何使用这款 Hello Kitty 小兵皮肤&#xff0c;今天小编将为大家整理出…

STC单片机与串口触摸屏通讯程序

/***串口1切换通讯测试,单片机发送数据给触摸屏***/ /***切换到3.0 3.1发送数据到串口通信软件 ***/ /***设置温度 加热时间读写EEPROM正确 ***/ #include <REG52.H> //2023 3 5 L330 CODE2667 #include <intrin…

使用JDK自带工具进行JVM内存分析之旅

进行jvm内存分析可以排查存在和潜在的问题。 通过借助jdk自带的常用工具&#xff0c;可以分析大概可能的问题定位以及确定优化方向。 JVM内存分析有很多好处。 内存泄漏排查&#xff1a;JVM 内存泄漏是指应用程序中的对象占用的内存无法被垃圾回收器释放&#xff0c;导致内存…

遥瞻智慧:排水系统远程监控的卓越解决方案

遥瞻智慧&#xff1a;排水系统远程监控的卓越解决方案 在城市脉络的深层肌理中&#xff0c;排水系统犹如一条条隐秘的生命线&#xff0c;默默承载着城市的呼吸与律动。然而&#xff0c;如何以科技之眼&#xff0c;赋予这些无形网络以实时感知、精准调控的能力&#xff0c;使之…

基于机器学习的车辆状态异常检测

基于马氏距离的车辆状态异常检测&#xff08;单一传感器&#xff09; 基于多元自动编码器的车辆状态异常检测 基于单传感器平滑马氏距离的车辆状态异常检测 工学博士&#xff0c;担任《Mechanical System and Signal Processing》等期刊审稿专家&#xff0c;擅长领域&#xff1…

数据分析场景,连号相关业务

连号相关业务 业务场景&#xff1a;现在需要从a列一堆编号中&#xff0c;将连号范围在10以内的数据分别分成一组。 先看实先效果 演示的为db2数据库&#xff0c;需要含有窗口函数&#xff0c;或者可以获取到当前数据偏移的上一位数据 第一步&#xff1a;将A列数据正序第二步…

量子密钥分发系统的设计与实现(三):量子信号的产生、调制及探测技术讨论

之前的文章我们对量子密钥分发系统功能的光路子系统进行了较为全面的分析&#xff0c;我们理解了光路子系统是量子密钥分发系统的基础。本文我们主要探讨下量子信号产生、调制及探测的基础技术&#xff0c;算是一篇承上启下的文章吧&#xff0c;对相关的原理进行探讨&#xff0…

如何使用 ArcGIS Pro 制作边界晕渲效果

在某些出版的地图中&#xff0c;边界有类似于“发光”的晕渲效果&#xff0c;这里为大家介绍一下如何使用ArcGIS Pro 制作这种晕渲效果&#xff0c;希望能对你有所帮助。 数据来源 教程所使用的数据是从水经微图中下载的行政区划数据&#xff0c;除了行政区划数据&#xff0c…

wsl2 Ubuntu子系统内存只有一半的解决办法

物理机的内存是64G&#xff0c;在wsl2安装完Ubuntu20.04后&#xff0c;输入命令&#xff1a; free -g 发现只有32G&#xff0c;原因是默认只能获得物理机一半的内存&#xff1a; WSL 中的高级设置配置 | Microsoft Learn 因此可手动修改为与物理机同等大小&#xff1a; 1&a…

如何解决DDoS攻击?群联科技做出回答。

DDoS攻击&#xff08;分布式拒绝服务攻击&#xff09;是一种恶意利用多台傀儡机协同发起大规模网络流量&#xff0c;旨在压垮目标系统或网络资源&#xff0c;使其无法正常服务的网络攻击手段。由于现代计算机和网络性能的提升&#xff0c;单点发起的DoS攻击已难以奏效&#xff…