酷代码 AI
菜单
服务商
DeepSeek字节豆包讯飞星火
更多选项

C# 巧用二分查找法:判断集合 b 是否为集合 a 的子集

在C#中,可以使用二分查找法来判断一个集合b是否是另一个集合a的子集。以下是使用二分查找法实现的示例代码: ```csharp using System; using System.Collections.Generic; class Program { static bool IsSubset(List<int> a, List<int> b) { a.Sort(); b.Sort(); foreach (int num in b) { if (BinarySearch(a, num) == -1) { return false; } } return true; } static int BinarySearch(List<int> list, int target) { int left = ; int right = list.Count - 1; while (left <= right) { int mid = left + (right - left) / 2; if (list[mid] == target) return mid; else if (list[mid] < target) left = mid + 1; else right = mid - 1; } return -1; } static void Main(string[] args) { List<int> a = new List<int>() { 6, 20, 84, 45, 12, 67, 9, 3 }; List<int> b = new List<int>() { 12, 694 }; bool isSubset = IsSubset(a, b); Console.WriteLine(isSubset); } } ``` 在这段代码中,我们首先对集合a和b进行排序,然后使用二分查找算法判断b中的每个元素是否在a中存在。如果b中有任何一个元素在a中不存在,就返回false;如果b中的所有元素都在a中存在,那么b就是a的子集,返回true。运行以上代码,输出结果为true。 ######[AI写代码神器 | 1174点数解答 | 2024-04-19 11:55:50]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]