C# 算法与数据结构:实践篇
\n\n理解算法与数据结构是每位开发者的基础技能。无论你是在编写高负载服务、桌面应用还是游戏,高效的数据管理直接影响代码的性能和可扩展性。在本文中,我们将通过实际示例,深入讲解 C# (.NET) 中的关键数据结构与算法,你可以立即将其应用到自己的项目中。
\n\n1. 动态数组与 List<T> 的使用
\n\n在 C# 中,基本的动态数组是 List<T> 类。与经典数组不同,它在添加元素时会自动扩展。下面我们来看它的关键操作,以及其中最重要的一个——二分查找。
二分查找 (Binary Search) 仅适用于已排序的数据。其时间复杂度为 O(log n)。该算法每一步都将搜索范围对半分割。
\n\nusing System;\nusing System.Collections.Generic;\n\npublic class BinarySearchExample\n{\n public static int BinarySearch(List<int> sortedList, int target)\n {\n int left = 0;\n int right = sortedList.Count - 1;\n\n while (left <= right)\n {\n int mid = left + (right - left) / 2;\n\n if (sortedList[mid] == target)\n return mid; // 找到元素,返回索引\n else if (sortedList[mid] < target)\n left = mid + 1; // 在右半部分查找\n else\n right = mid - 1; // 在左半部分查找\n }\n return -1; // 未找到元素\n }\n\n public static void Main()\n {\n var numbers = new List<int> { 2, 5, 8, 12, 16, 23, 38, 45, 56, 67 };\n int target = 23;\n int result = BinarySearch(numbers, target);\n Console.WriteLine(result != -1 ? $"元素 {target} 在索引 {result} 处找到" : "未找到元素");\n }\n}\n\n为什么这很重要? List<T> 在 90% 的项目中都有使用。能够快速在其中查找数据是提升性能的关键。
\n\n2. 栈与队列:LIFO 和 FIFO 的实际应用
\n\n栈 (Stack) 和队列 (Queue) 是具有明确访问顺序的集合。它们在处理调用、语法分析和任务管理时不可或缺。
\n\n栈 (LIFO — 后进先出)
\n例如,用于检查代码中括号的正确性。
\n\nusing System;\nusing System.Collections.Generic;\n\npublic class StackExample\n{\n public static bool IsValidBrackets(string input)\n {\n Stack<char> stack = new Stack<char>();\n foreach (char ch in input)\n {\n if (ch == '(' || ch == '{' || ch == '[')\n {\n stack.Push(ch);\n }\n else if (ch == ')' || ch == '}' || ch == ']')\n {\n if (stack.Count == 0) return false;\n\n char top = stack.Pop();\n if ((ch == ')' && top != '(') ||\n (ch == '}' && top != '{') ||\n (ch == ']' && top != '['))\n {\n return false;\n }\n }\n }\n return stack.Count == 0;\n }\n\n public static void Main()\n {\n string test1 = "({[]})";\n string test2 = "({[})";\n Console.WriteLine($"'{test1}' — 括号正确: {IsValidBrackets(test1)}");\n Console.WriteLine($"'{test2}' — 括号正确: {IsValidBrackets(test2)}");\n }\n}\n\n队列 (FIFO — 先进先出)
\n非常适合按任务到达的顺序进行处理(例如打印队列)。
\n\nusing System;\nusing System.Collections.Generic;\n\npublic class QueueExample\n{\n public static void Main()\n {\n