算法学习-基础数据结构

news2024/9/23 19:18:01

基础数据结构

一.栈

1.普通栈

套路:从前往后遍历 + 需要考虑相邻元素 + 有消除操作 = 栈。

2.单调栈

二.队列

1.普通队列

2.优先队列

三.Trie

使用场景:可以求某个字符串在众多字符串中出现的次数,以某个字符串为前缀出现的次数
Trie中,Trie数组是必须得,其他的根据业务场景决定(如:isEnd,count等)
在这里插入图片描述
模版1

class Trie {
    Trie[] children;
    boolean isEnd;
    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
        Trie node = this;
        for(char c : word.toCharArray()){
            int index = c - 'a';
            if(node.children[index]==null){
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }

        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = this;
        for(char c : word.toCharArray()){
            int index = c - 'a';
            if(node.children[index]==null){
                return false;
            }
            node = node.children[index];
        }
        return node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        Trie node = this;
        for(char c : prefix.toCharArray()){
            int index = c - 'a';
            if(node.children[index]==null){
                return false;
            }
            node = node.children[index];
        }
        return true;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

模版2

class Trie {
    Trie[] child = new Trie[26];
    int ref = -1;

    void insert(String word, int ref) {
        Trie node = this;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.child[index] == null) {
                node.child[index] = new Trie();
            }
            node = node.child[index];
        }

        node.ref = ref;
    }

    int search(String word) {
        Trie node = this;
        for (char c : word.toCharArray()) {
            int index = c - 'a';
            if (node.child[index] == null) {
                return -1;
            }
            node = node.child[index];
            //注意:判断都是在node = node.child[index];之后判断
            if (node.ref != -1) {
                return node.ref;
            }
        }
        return -1;
    }

    
}

LeetCode例题

四.并查集

1.逆序思维,删除–合并
2.传递性

1.普通并查集

class UF{
    int[] parent;
    int[] size;
    int count ;
    UF(int n){
        parent = new int[n];
        size = new int[n];
        count = n;
        for(int i = 0;i<n;i++){
            parent[i] = i;
            size[i] = 1;
        }
    }

    void union(int p,int q){
        int rootP = find(p);
        int rootQ = find(q);
        if(rootP==rootQ){
            return;
        }
        if(size[rootP]>size[rootQ]){
            parent[rootQ] = rootP;
            size[rootP] += size[rootQ];
        }else{
            parent[rootP] = rootQ;
            size[rootQ] += size[rootP];
        }
        count--;
    }

    int find(int x){
        if(parent[x]!=x){
            parent[x] = find(parent[x]);
        }

        return parent[x];
    }

    boolean connect(int p,int q){
        return find(p)==find(q);
    }

    int size(int x){
        return size[x];
    }

    int count(){
        return count;
    }
}

2.map实现并查集

LeetCode例题

class Solution {
    public boolean areSentencesSimilarTwo(String[] sentence1, String[] sentence2, List<List<String>> similarPairs) {
        UF uf = new UF();
        for(List<String> str : similarPairs){
            uf.union(str.get(0),str.get(1));
        }
        int m = sentence1.length;
        int n = sentence2.length;
        if(m!=n){
            return false;
        }
        for(int i = 0;i<n;i++){
            if(!uf.connected(sentence1[i],sentence2[i])){
                return false;
            }
        }

        return true;
    }
}

class UF{
    HashMap<String,String> map = new HashMap<>();

    void union(String p,String q){
        String rootP = find(p);
        String rootQ = find(q);

        if(!rootP.equals(rootQ)){
            map.put(rootP,rootQ);
        }
    }

    boolean connected(String p,String q){
        return find(p).equals(find(q));
    }

    String find(String x){
        while(map.containsKey(x)&&map.get(x)!=x){
            x = map.get(x);
        }
        return x;
    }
}

3.并查集结合map记录父结点信息

LeetCode例题

class Solution {
    public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) {
        int n = s.length();
        UF uf = new UF(n);
        for(List<Integer> list : pairs){
            uf.union(list.get(0),list.get(1));
        }
        HashMap<Integer,PriorityQueue<Character>> map = new HashMap<>();
        for(int i = 0;i<n;i++){
            int j = uf.find(i);
            map.computeIfAbsent(j,k->new PriorityQueue<>()).offer(s.charAt(i));
        }

        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<n;i++){
            PriorityQueue<Character> q = map.get(uf.find(i));
            sb.append(q.poll());
        }

        return sb.toString();
    }
}

class UF{
    int[] parent;

    UF(int n){
        parent = new int[n];
        for(int i = 0;i<n;i++){
            parent[i] = i;
        }
    }

    void union(int p,int q){
        int rootP = find(p);
        int rootQ = find(q);
        if(rootP==rootQ){
            return;
        }
        parent[rootP] = rootQ;
    }

    int find(int x){
        if(x!=parent[x]){
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
}

4.公因数并查集

LeetCode例题

class Solution {
    public boolean canTraverseAllPairs(int[] nums) {
        UF uf = new UF(100001);
        if(nums.length==1){
            return true;
        }
        for(int num : nums){
            if(num==1){
                return false;
            }
            int t = num;
            for(int i = 2;i*i<=num;i++){
                if(num%i==0){
                    uf.union(t,i);
                    while(num%i==0){
                        num /= i;
                    }
                }

                if(num>1){
                    uf.union(t,num);
                }
            }
        }
        int r = uf.find(nums[0]);
        for(int num : nums){
            if(uf.find(num)!=r){
                return false;
            }
        }

        return true;
    }
}

class UF{
    int[] parent;

    UF(int n){
        parent = new int[n];
        for(int i = 0;i<n;i++){
            parent[i] = i;
        }
    }

    void union(int p,int q){
        int rootP = find(p);
        int rootQ = find(q);
        if(rootP==rootQ){
            return;
        }
        parent[rootP] = rootQ;
    }

    int find(int x){
        if(x!=parent[x]){
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }
}

LeetCode3和4综合练习题

5.边权并查集

LeetCode例题

class Solution {
    public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
        int n = equations.size();
        UF uf = new UF(2 * n);
        HashMap<String, Integer> map = new HashMap<>();
        int id = 0;
        for (int i = 0; i < n; i++) {
            List<String> equation = equations.get(i);
            String val1 = equation.get(0);
            String val2 = equation.get(1);

            if (!map.containsKey(val1)) {
                map.put(val1, id);
                id++;
            }
            if (!map.containsKey(val2)) {
                map.put(val2, id);
                id++;
            }
            uf.union(map.get(val1), map.get(val2), values[i]);
        }
        int queriesSize = queries.size();
        double[] res = new double[queriesSize];
        for (int i = 0; i < queriesSize; i++) {
            String val1 = queries.get(i).get(0);
            String val2 = queries.get(i).get(1);

            Integer id1 = map.get(val1);
            Integer id2 = map.get(val2);

            if (id1 == null || id2 == null) {
                res[i] = -1.0;
            } else {
                res[i] = uf.isConnected(id1, id2);
            }
        }
        return res;
    }
}

class UF {
    int[] parent;
    double[] weight;

    UF(int n) {
        parent = new int[n];
        weight = new double[n];
        for (int i = 0; i < n; i++) {
            parent[i] = i;
            weight[i] = 1.0;
        }
    }

    void union(int p, int q, double value) {
        int rootP = find(p);
        int rootQ = find(q);
        if (rootP == rootQ) {
            return;
        }
        parent[rootP] = rootQ;
        weight[rootP] = weight[q] * value / weight[p];
    }

    int find(int x) {
        if (x != parent[x]) {
            int origin = parent[x];
            parent[x] = find(parent[x]);
            weight[x] *= weight[origin];
        }
        return parent[x];
    }

    double isConnected(int p, int q) {
        int rootP = find(p);
        int rootQ = find(q);
        if (rootP == rootQ) {
            return weight[p] / weight[q];
        }
        return -1.0;
    }
}

相关题目:
1.LeetCode
2.LeetCode
3.LeetCode

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

设计一个最小栈

问题 请你设计一个 最小栈 。它提供 push &#xff0c;pop &#xff0c;top 操作&#xff0c;并能在常数时间内检索到最小元素的栈。 实现 MinStack 类: MinStack() 初始化堆栈对象。void push(int val) 将元素val推入堆栈。void pop() 删除堆栈顶部的元素。int top() 获取堆…

昂科烧录器支持MindMotion灵动微电子的微控制器MM32F5333D7P

芯片烧录行业领导者-昂科技术近日发布最新的烧录软件更新及新增支持的芯片型号列表&#xff0c;其中MindMotion灵动微电子的32位微控制器MM32F5333D7P已经被昂科的通用烧录平台AP8000所支持。 MM32F5333D7P微控制器搭载了由安谋科技授权的Armv8-M架构“星辰”STAR-MC1处理器&a…

Redux的中间件原理分析

Redux的中间件原理分析 redux的中间件对于使用过redux的各位都不会感到陌生&#xff0c;通过应用上我们需要的所有要应用在redux流程上的中间件&#xff0c;我们可以加强dispatch的功能。最近抽了点时间把之前整理分析过的中间件有关的东西放在这里分享分享。本文只对中间件涉…

在线客服系统源码 完全开源可二开 带完整的安装代码包以及搭建部署教程

系统概述 在线客服系统是一种基于互联网技术的客户服务解决方案&#xff0c;通过即时通讯工具&#xff0c;如文本聊天、语音通话、视频交流等方式&#xff0c;实现企业与客户之间的实时互动。它打破了传统客服模式的时空限制&#xff0c;使客户能够在任何时间、任何地点获得快…

Java基础(4)- IDEA

目录 一、Module 1.创建module 2.关闭modue 3.导入module 4.src灰色 二、Package 1.创建package 2.删除package 3.package取名规范 三、类 1.创建类 2.快捷语法 3.HelloWorld 四、IDEA基本设置说明 1.字体 2.提示的快捷键 五、常用快捷键 一、Module 1.创建mod…

Python大数据之Hadoop学习——day05_hive基本操作

一.SQL,Hive和MapReduce的关系 用户在hive上编写sql语句&#xff0c;hive把sql语句转为mapreduce程序去执行 二.Hive的架构映射流程 三.MetaStore元数据管理三种模式 metastore服务配置有3种&#xff1a; 内嵌模式、本地模式、远程模式&#xff08;推荐&#xff09; 内嵌模式…

【一文读懂】基于Havenask向量检索+大模型,构建可靠的智能问答服务

Havenask是阿里巴巴智能引擎事业部自研的开源高性能搜索引擎&#xff0c;深度支持了包括淘宝、天猫、菜鸟、高德、饿了么在内的几乎整个阿里的搜索业务。本文针对性介绍了Havenask作为一款高性能的召回搜索引擎&#xff0c;应用在向量检索和LLM智能问答场景的解决方案和核心优势…

泰山派小手机---ubuntu 环境的搭建

问题&#xff1a; 本来我的 泰山派的 ubuntu 虚拟机环境已经搭建好了&#xff0c;但是由于一直到捣鼓 neovim &#xff0c;把虚拟机 内核搞崩溃&#xff0c;所以从新安装一下 虚拟机。 过程&#xff1a; 1 首先是 安装虚拟机。 下载镜像。 https://mirrors.ustc.edu.cn/ubu…

密码强度验证——js基础积累

//密码强度等级 getPwdLevel:function (pwd,minLength8) {var level 0;if (pwd.length < minLength) return level;if (/\d/.test(pwd)) level; //数字if (/[a-z]/.test(pwd)) level; //小写if (/[A-Z]/.test(pwd)) level; //大写if (/\W/.test(pwd)) level; //特殊字符ret…

安卓好软-----手机端提取apk的小工具 方便简单 无需root权限

apk提取工具 工具小巧。可以提取手机上面当前安装的apk和系统应用apk。而且无需root权限即可正常使用。 效果非常不错。比其他工具提取系统app方便好使。 下载&#xff1a;https://download.csdn.net/download/mg668/89683199?spm1001.2014.3001.5503

副业赚钱新玩法:大模型也能月入过万?

在这个多元化的时代&#xff0c;副业已经成为了越来越多人的选择。无论是为了实现个人兴趣&#xff0c;还是为了增加收入来源&#xff0c;副业都为我们提供了无限可能。而随着人工智能技术的飞速发展&#xff0c;利用大模型来开展副业也成为了一种新兴的方式。今天&#xff0c;…

日常避坑指南:如何正确使用 aiohttp 上传文件,避免文件被提前关闭

在日常开发中,我们经常会遇到需要上传文件到服务器的场景。如果你选择使用 aiohttp 进行异步请求,上传文件的方式需要特别注意,否则可能会遇到一些令人头疼的问题——比如文件被提前关闭,导致上传失败。这篇文章将为你详细解析这个问题,并提供有效的解决方案,帮助你在开发…

Mysql基础练习题 181.找到收入比经理高的员工 (力扣)

181.找到收入比经理高的员工 建表插入数据&#xff1a; Create table If Not Exists Employee (id int, name varchar(255), salary int, managerId varchar(10)); Truncate table Employee insert into Employee (id, name, salary, managerId) values (1, Joe, 70000, 3); …

/lib64/libm.so.6: version `GLIBC_2.27‘ not found 如何解决?

安装GLIBC_2.27 wget http://ftp.gnu.org/gnu/glibc/glibc-2.27.tar.gz tar xf glibc-2.27.tar.gz cd glibc-2.27/ && mkdir build && cd build ../configure --prefix/usr --disable-profile --enable-add-ons --with-headers/usr/include --with-binutils…

聚观早报 | 智界R7亮相;问界新M7 Pro正式上市

聚观早报每日整理最值得关注的行业重点事件&#xff0c;帮助大家及时了解最新行业动态&#xff0c;每日读报&#xff0c;就读聚观365资讯简报。 整理丨Cutie 8月28日消息 智界R7亮相 问界新M7 Pro正式上市 《全职高手3》动画热播 苹果2024秋季发布会官宣 一加Ace 5 Pro设…

火语言RPA流程组件介绍--播放声音

&#x1f6a9;【组件功能】&#xff1a;播放系统声音或指定的Wav格式声音文件 配置预览 配置说明 来源 系统&#xff1a;播放Windows系统内置声音。 自定义Wav文件&#xff1a;播放本地路径下指定声音文件。 Wav文件 支持T或# 默认FLOW输入项 选择Wav声音文件的本地路径。…

35岁零基础转战AI领域:实现AI大模型开发者职业转型的可能性与路径

以下从3个方面帮大家分析&#xff1a; 35岁转行会不会太晚&#xff1f;零基础学习AI大模型开发能不能学会&#xff1f;AI大模型开发行业前景如何&#xff0c;学完后能不能找到好工作&#xff1f; 一、35岁转行会不会太晚&#xff1f; 35岁正处于人生的黄金时期&#xff0c;拥…

灵魂 20 问帮你彻底搞定Transformer

1.Transformer为何使用多头注意力机制&#xff1f;&#xff08;为什么不使用一个头&#xff09; 捕捉多种依赖关系&#xff1a; 多头注意力机制允许模型同时关注输入数据的不同部分和特征。每个“头”都能够学习输入序列的不同表示子空间&#xff0c;从而捕捉到不同类型的依赖关…

大模型落地难点之结构化输出

应用至上 2023年的世界人工智能大会&#xff08;WAIC&#xff09;是“百模大战”&#xff0c;今年WAIC的关键词是“应用至上”。纵观今年论坛热点话题&#xff0c;无论是具身智能还是AI Agent&#xff08;智能体&#xff09;&#xff0c;都指向以大模型为代表的AI技术在不同场…

一文道尽 RAG,为大模型提供你的私有知识

什么是 RAG&#xff1f;先说一个你可能不相信的事实&#xff1a;RAG 是2005年提出的古老技术&#xff08;论文在此 https://arxiv.org/pdf/2005.11401&#xff09;。然后我们先看一个学术定义&#xff1a;“检索增强生成&#xff08;Retrieval-augmented Generation&#xff09…