C#中提供的多种集合类以及适用场景

在 C# 中,有多种集合类可供使用,它们分别适用于不同的场景,部分代码示例提供了LeetCode相关的代码应用。

1. 数组(Array)

  • 特点
    • 固定大小:在创建数组时需要指定其长度,之后无法动态改变。
    • 连续存储:数组元素在内存中是连续存储的,因此可以通过索引快速访问元素,访问时间复杂度为 O(1)。
    • 类型固定:数组中的所有元素必须是相同类型。
  • 示例代码
  int[] numbers = new int[5] { 1, 5, 2, 3, 4 };numbers[0] = 1;//updateint firstNumber = numbers[0];int lastNumber = numbers[numbers.Length - 1];Array.Sort(numbers);//排序

LeetCode: 106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)

public TreeNode BuildTree(int[] inorder, int[] postorder)
{if (inorder.Length == 0 || postorder.Length == null) return null;int rootValue = postorder.Last();TreeNode root = new TreeNode(rootValue);int delimiterIndex = Array.IndexOf(inorder, rootValue);root.left = BuildTree(inorder.Take(delimiterIndex).ToArray(), postorder.Take(delimiterIndex).ToArray());root.right = BuildTree(inorder.Skip(delimiterIndex + 1).ToArray(), postorder.Skip(delimiterIndex).Take(inorder.Length - delimiterIndex - 1).ToArray());return root;
}

2. 动态数组(List<T>)

  • 特点
    • 动态大小:可以根据需要动态添加或删除元素,无需预先指定大小。
    • 连续存储:内部使用数组实现,元素在内存中连续存储,支持通过索引快速访问,访问时间复杂度为 O(1)。
    • 类型安全:泛型集合,只能存储指定类型的元素。
  • 示例代码
List<int> numberList = new List<int>();
numberList.Add(1);
int firstElement = numberList[0];

3. 链表(LinkedList<T>)

  • 特点
    • 动态大小:可以动态添加或删除元素。
    • 非连续存储:元素在内存中不连续存储,每个元素包含一个指向前一个元素和后一个元素的引用。
    • 插入和删除效率高:在链表的任意位置插入或删除元素的时间复杂度为 O(1),但随机访问效率低,时间复杂度为O(n) 。
  • 示例代码
            LinkedList<int> numberLinkedList = new LinkedList<int>();numberLinkedList.AddLast(1);numberLinkedList.AddFirst(2);numberLinkedList.AddFirst(3);numberLinkedList.Remove(1);numberLinkedList.RemoveFirst();numberLinkedList.RemoveLast();int count=numberLinkedList.Count;bool isContains= numberLinkedList.Contains(3);

4. 栈(Stack<T>)

  • 特点
    • 后进先出(LIFO):最后添加的元素最先被移除。
    • 动态大小:可以动态添加或删除元素。
    • 插入和删除操作快:入栈(Push)和出栈(Pop)操作的时间复杂度为O(1) 。
  • 示例代码
            Stack<int> numberStack = new Stack<int>();numberStack.Push(1);// Removes and returns the object at the top of the System.Collections.Generic.Stack`1.int topElement = numberStack.Pop();// Returns the object at the top of the System.Collections.Generic.Stack`1 without removing it.topElement = numberStack.Peek(); int count = numberStack.Count;

LeetCode: 144. 二叉树的前序遍历

/*** Definition for a binary tree node.* public class TreeNode {*     public int val;*     public TreeNode left;*     public TreeNode right;*     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
public class Solution {public IList<int> PreorderTraversal(TreeNode root) {var result = new List<int>();if (root == null) return result;Stack<TreeNode> treeNodes = new Stack<TreeNode>();// 栈是先进后出。 中序遍历是:中--》 左--》右treeNodes.Push(root);while (treeNodes.Count > 0){TreeNode current = treeNodes.Pop();result.Add(current.val);// 中if (current.right != null)// 右{treeNodes.Push(current.right);}if (current.left != null)// 左{treeNodes.Push(current.left);}}return result;}
}

5. 队列(Queue<T>)

  • 特点
    • 先进先出(FIFO):最先添加的元素最先被移除。
    • 动态大小:可以动态添加或删除元素。
    • 插入和删除操作快:入队(Enqueue)和出队(Dequeue)操作的时间复杂度为 O(1)。
  • 示例代码
          Queue<int> numberQueue = new Queue<int>();numberQueue.Enqueue(1);// Removes and returns the object at the beginning of the System.Collections.Generic.Queue`1.int firstElement = numberQueue.Dequeue();//Returns the object at the beginning of the System.Collections.Generic.Queue`1 without removing it.numberQueue.Peek();int count = numberQueue.Count;

LeetCode: 102. 二叉树的层序遍历 - 力扣(LeetCode) 

/*** Definition for a binary tree node.* public class TreeNode {*     public int val;*     public TreeNode left;*     public TreeNode right;*     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
public class Solution {public IList<IList<int>> LevelOrder(TreeNode root) {var result = new List<IList<int>>();Queue<TreeNode> queue = new ();if (root != null) queue.Enqueue(root);while (queue.Count>0){var row=new List<int>();int count=queue.Count;// 需要事先记录Queue的Count,不能直接依靠Queue本身for (int i=0; i < count; i++){var currentNode=queue.Dequeue();row.Add(currentNode.val);if (currentNode.left != null) queue.Enqueue(currentNode.left);if (currentNode.right != null) queue.Enqueue(currentNode.right);}result.Add(row);}return result;}
}

6. 哈希集合(HashSet<T>)

  • 特点
    • 唯一元素:集合中不允许有重复的元素。
    • 无序:元素在集合中没有特定的顺序。
    • 快速查找:插入、删除和查找操作的平均时间复杂度为O(1) 。
  • 示例代码
      HashSet<int> numberHashSet = new HashSet<int>();numberHashSet.Add(1);bool isAddSuccess = numberHashSet.Add(1);// falsebool containsOne = numberHashSet.Contains(1);// true

如LeetCode:491. 非递减子序列

public class Solution {public IList<IList<int>> FindSubsequences(int[] nums) {var result = new List<IList<int>>();var path = new List<int>();if(nums==null || nums.Length == 0) return result;BackTacking(nums,result,path,0);return result;}private void BackTacking(int[] nums,List<IList<int>> result, List<int> path,int startIndex){if (path.Count>=2) result.Add(new List<int>(path));HashSet<int> used =new HashSet<int>();for (int i=startIndex;i<nums.Length;i++){if(path.Count>0 && nums[i]<path[path.Count-1]) continue;bool isUsed=used.Add(nums[i]);// true-添加成功;false-添加失败,证明已经有元素存在了if(!isUsed) continue;// 同一层重复使用path.Add(nums[i]);BackTacking(nums,result,path,i+1);path.RemoveAt(path.Count-1);}}
}

7. 字典(Dictionary<TKey, TValue>)

  • 特点
    • 键值对存储:通过唯一的键来关联对应的值。
    • 快速查找:根据键查找值的平均时间复杂度为  O(1)。
    • 键唯一:字典中的键必须是唯一的,但值可以重复。
  • 示例代码
Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 90);
int aliceScore = scores["Alice"];

LeetCode: 105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)

/*** Definition for a binary tree node.* public class TreeNode {*     public int val;*     public TreeNode left;*     public TreeNode right;*     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
public class Solution {public TreeNode BuildTree(int[] preorder, int[] inorder){if (preorder == null || inorder == null){return null;}/*前序遍历   根   左子树 右子树中序遍历   左子树 根   右子树*/if (preorder.Length != inorder.Length){return null;}Dictionary<int, int> keyMap = new Dictionary<int, int>();for (int i = 0; i < inorder.Length; i++){keyMap.Add(inorder[i], i);}return BuildTree(preorder: preorder, keyMap, preleft: 0, preRight: preorder.Length - 1, inLeft: 0, inRight: inorder.Length - 1);}/// <summary>/// /// </summary>/// <param name="preorder"></param>/// <param name="keyMap">用于确定pIndex。Root的Index</param>/// <param name="preleft"></param>/// <param name="preRight"></param>/// <param name="inLeft"></param>/// <param name="inRight"></param>/// <returns></returns>private TreeNode BuildTree(int[] preorder, Dictionary<int, int> keyMap, int preleft, int preRight, int inLeft, int inRight){if (preleft > preRight || inLeft > inRight){return null;}int rootValue = preorder[preleft];TreeNode treeNode = new TreeNode(rootValue);int pIndex = keyMap[rootValue];treeNode.left = BuildTree(preorder, keyMap, preleft: preleft + 1, preRight: pIndex + preleft - inLeft, inLeft, inRight: pIndex - 1);//根据PreOrder去取Left nodetreeNode.right = BuildTree(preorder, keyMap, preleft: pIndex + preleft - inLeft + 1, preRight: preRight, inLeft: pIndex + 1, inRight);//根据inOrder去取Right nodereturn treeNode;}
}

8. 排序集合(SortedSet<T>)

  • 特点
    • 唯一元素:集合中不允许有重复的元素。
    • 有序:元素会根据元素的自然顺序或指定的比较器进行排序。
    • 查找和插入操作:插入、删除和查找操作的时间复杂度为 O(logn)。
  • 示例代码
SortedSet<int> sortedNumbers = new SortedSet<int>();
sortedNumbers.Add(3);
sortedNumbers.Add(1);
// 元素会自动排序,遍历输出为 1, 3
foreach (int number in sortedNumbers)
{Console.WriteLine(number);
}

9. 排序字典(SortedDictionary<TKey, TValue>)

  • 特点
    • 键值对存储:通过唯一的键来关联对应的值。
    • 有序:元素会根据键的自然顺序或指定的比较器进行排序。
    • 查找和插入操作:根据键查找值、插入和删除操作的时间复杂度为  O(logn)。
  • 示例代码
SortedDictionary<string, int> sortedScores = new SortedDictionary<string, int>();
sortedScores.Add("Evan", 38);
sortedScores.Add("Alice", 30);
// 会根据键排序,遍历输出 Alice: 30, Evan: 38
foreach (KeyValuePair<string, int> pair in sortedScores)
{Console.WriteLine($"{pair.Key}: {pair.Value}");
}

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

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

相关文章

5秒修改文件默认打开方式-windows版

这里写自定义目录标题 今天做前端开发遇见我的ts文件默认打开方式是暴风影音&#xff0c;但是我想让他默认用vscode打开&#xff0c;在vscode 找了半天也没搞定&#xff0c;从网上搜索到了修改方式&#xff0c;只需5秒钟。下面就来看看吧。 &#x1f4c1; 想要改变文件的默认打…

2025年信息科学与工程学院科协机器学习介绍——机器学习基本模型介绍

机器学习 目录 机器学习一.安装基本环境conda/miniconda环境 二.数据操作数据预处理一维数组二维数组以及多维数组的认识访问元素的方法torch中tenson的应用张量的运算张量的广播 三.线性代数相关知识四.线性回归SoftMax回归问题&#xff08;分类问题&#xff09;什么是分类问题…

计算机毕业设计Hadoop+Spark+DeepSeek-R1大模型民宿推荐系统 hive民宿可视化 民宿爬虫 大数据毕业设计(源码+文档+PPT+讲解)

温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 温馨提示&#xff1a;文末有 CSDN 平台官方提供的学长联系方式的名片&#xff01; 作者简介&#xff1a;Java领…

业务应用和大数据平台的数据流向

概述 业务应用与大数据平台之间的交互是实现数据驱动决策和实时业务处理的关键环节。其交互方式多样&#xff0c;协议选择取决于数据流向、实时性要求及技术架构。一句话总结&#xff0c;数据流向可以是从业务应用写入大数据平台&#xff0c;也可以是大数据平台回写至业务应用…

山东大学软件学院nosql实验一环境配置

环境&#xff1a;前端vue后端springboot 软件环境&#xff1a; MongoDB MongoDBCompass 实验步骤与内容&#xff1a; 在官网下载安装包&#xff08;最新版&#xff09; 配置环境环境变量 在“高级系统设置-环境变量”中&#xff0c;可以将MongoDB添加到环境变量Path中(D:\…

《计算机视觉》——图像拼接

图像拼接 图像拼接是将多幅有重叠区域的图像合并成一幅全景或更大视角图像的技术&#xff0c;以下为你详细介绍&#xff1a; 原理&#xff1a;图像拼接的核心原理是基于图像之间的特征匹配。首先&#xff0c;从每幅图像中提取独特的特征点&#xff0c;如角点、边缘点等&#x…

后台管理系统-园区管理

功能演示和模版搭建 <template><div class"building-container"><!-- 搜索区域 --><div class"search-container"><div class"search-label">企业名称&#xff1a;</div><el-input clearable placeholde…

CSS中padding和margin属性的使用

在 HTML 中&#xff0c;padding 和 margin 是用于控制元素布局和间距的重要属性。 一、Padding&#xff08;内边距&#xff09; 定义&#xff1a;Padding 是指元素内容与元素边框之间的距离。它可以在元素内部创造出空白区域&#xff0c;使得内容不会紧贴着边框。 作用 增加元…

git中,如何查看具体单个文件的log

在 Git 中&#xff0c;可以使用多种方式查看单个文件的提交日志&#xff08;Log&#xff09;&#xff0c;以下详细介绍不同场景下的查看方法&#xff1a; 目录 一、基本命令查看文件的完整提交日志 二、查看文件提交日志并显示差异内容 三、限制显示的提交日志数量 四、按…

日常知识点之刷题一

1&#xff1a;流浪地球 0~n-1个发动机&#xff0c;计划启动m次&#xff0c;求最后启动的发动机的个数。 以及发动机的编号。&#xff08;模拟过程&#xff0c;每次手动启动的机器对应时间向两边扩散&#xff09; //输入每个启动的时间和编号 void test_liulang() {int n, m;ci…

C++面向对象编程技术研究

一、引言 面向对象编程&#xff08;OOP&#xff09;是一种程序设计方法&#xff0c;它将现实世界中的实体抽象为“对象”&#xff0c;并通过类和对象来实现程序的设计。OOP的核心思想包括封装、继承和多态&#xff0c;这些特性使得程序更加模块化、易于扩展和维护。C作为一种支…

Day54(补)【AI思考】-SOA,Web服务以及无状态分步解析与示例说明

文章目录 **SOA&#xff0c;Web服务以及无状态**分步解析与示例说明**分步解析与示例说明****1. 核心概念解析****2. 为什么说SOA与Web服务是“正交的”&#xff1f;****3. 架构风格 vs. 实现技术****4. 接口&#xff08;Interface&#xff09;的核心作用****5. Web服务的“被认…

【Deepseek高级使用教程】Deepseek-R1的5种高级进阶玩法,5分钟教会你Deepseek+行业的形式进行工作重构的保姆级教程

AI视频生成&#xff1a;小说文案智能分镜智能识别角色和场景批量Ai绘图自动配音添加音乐一键合成视频https://aitools.jurilu.com/ 最近&#xff0c;有各行各业的小伙伴问我&#xff0c;到底应该怎么将deepseek融入进他们自身的工作流呢&#xff1f;其实这个问题很简单。我就以…

selenium爬取苏宁易购平台某产品的评论

目录 selenium的介绍 1、 selenium是什么&#xff1f; 2、selenium的工作原理 3、如何使用selenium&#xff1f; webdriver浏览器驱动设置 关键步骤 代码 运行结果 注意事项 selenium的介绍 1、 selenium是什么&#xff1f; 用于Web应用程序测试的工具。可以驱动浏览…

[实现Rpc] 客户端 | Requestor | RpcCaller的设计实现

目录 Requestor类的实现 框架 完善 onResponse处理回复 完整代码 RpcCaller类的实现 1. 同步调用 call 2. 异步调用 call 3. 回调调用 call Requestor类的实现 &#xff08;1&#xff09;主要功能&#xff1a; 客户端发送请求的功能&#xff0c;进行请求描述对服务器…

P2889 [USACO07NOV] Milking Time S

题目大意 有 N N N 个小时可以挤奶。其中有 m m m 个时间段可以给 Bessis 奶牛挤奶。第 i i i 个时间段为 s i s_i si​ ~ t i t_i ti​&#xff0c;可以获得 E f f i Eff_i Effi​ 滴奶。每次挤完奶后&#xff0c;人都要休息 R R R 小时。最后问&#xff0c;一共能挤出…

ONNX转RKNN的环境搭建和部署流程

将ONNX模型转换为RKNN模型的过程记录 工具准备 rknn-toolkit:https://github.com/rockchip-linux/rknn-toolkit rknn-toolkit2:https://github.com/airockchip/rknn-toolkit2 rknn_model_zoo:https://github.com/airockchip/rknn_model_zoo ultralytics_yolov8:https://github…

20250221 NLP

1.向量和嵌入 https://zhuanlan.zhihu.com/p/634237861 encoder的输入就是向量&#xff0c;提前嵌入为向量 二.多模态文本嵌入向量过程 1.文本预处理 文本tokenizer之前需要预处理吗&#xff1f; 是的&#xff0c;文本tokenizer之前通常需要对文本进行预处理。预处理步骤可…

C++基础知识学习记录—多态

1、函数覆盖 函数覆盖也被称为函数重写&#xff0c;类似于函数隐藏&#xff0c; 函数覆盖是多态的前提条件之一。 函数覆盖与函数隐藏的区别&#xff1a; ● 基类的被覆盖函数需要使用virtual关键字修饰&#xff0c;表示这个函数是一个虚函数 在Qt Creator中虚函数是斜体 虚…

GoFly框架中集成Bolt 和badfer两个Go语言嵌入式键值数据库

本插件集成了Bolt 和badfer两个纯Go实现的快速的嵌入式K/V数据库&#xff0c;方便开发时本地存储使用。插件集成Bolt 和badfer两个&#xff0c;如果确定使用其中一个&#xff0c;也可以把其中不用的一个删除&#xff0c;不删除也不会有任何影响。 插件使用说明 1.安装插件 到…