数学:HashSet 的并集
本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 62 课,共 66 课。
并集运算会合并两个集合,创建一个包含这两个集合中所有元素且不含重复项的新集合。
创建两个 HashSet:
HashSet<int> set1 = new HashSet<int>() { 1, 2, 3 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5 };使用 Union 方法合并集合:
HashSet<int> unionSet = new HashSet<int>(set1);
unionSet.UnionWith(set2);执行上面的代码后,unionSet 中包含:
[1, 2, 3, 4, 5]请注意,元素 3 在结果中只出现一次,因为 HashSet 不允许重复元素。
挑战
简单创建一个名为 UnionSets 的方法,它接收两个整数 HashSet 作为参数,并返回一个包含这两个集合并集的新 HashSet。
输入读取和输出打印已为你处理好:请专注于实现 UnionSets 方法体。
亲手试试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
class Program
{
public static HashSet<int> UnionSets(HashSet<int> set1, HashSet<int> set2)
{
// 在这里编写你的代码
return null;
}
static void Main(string[] args)
{
// 读取第一行,检查第一个集合的格式
string line1 = Console.ReadLine();
HashSet<int> set1 = new HashSet<int>();
// 检查第一个集合是否为 JSON 数组格式
if (line1 != null && line1.StartsWith("[") && line1.EndsWith("]"))
{
try
{
// 提取方括号内的内容
string arrayContent = line1.Substring(1, line1.Length - 2);
// 尝试解析 JSON 数组内容
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values)
{
// 如果有引号,就将其去掉
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
{
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// 解析为整数并添加到集合中
if (int.TryParse(cleanValue, out int num))
{
set1.Add(num);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing first set: {ex.Message}");
return;
}
}
else
{
// 处理第一个集合以空格分隔的传统输入
string[] input1 = line1.Split(' ');
foreach (string num in input1)
{
if (int.TryParse(num, out int parsedNum))
{
set1.Add(parsedNum);
}
}
}
// 读取第二行,检查第二个集合的格式
string line2 = Console.ReadLine();
HashSet<int> set2 = new HashSet<int>();
// 检查第二个集合是否为 JSON 数组格式
if (line2 != null && line2.StartsWith("[") && line2.EndsWith("]"))
{
try
{
// 提取方括号内的内容
string arrayContent = line2.Substring(1, line2.Length - 2);
// 尝试解析 JSON 数组内容
string[] values = Regex.Split(arrayContent, @",\s*");
foreach (string value in values)
{
// 如果有引号,就将其去掉
string cleanValue = value.Trim();
if (cleanValue.StartsWith("\"") && cleanValue.EndsWith("\""))
{
cleanValue = cleanValue.Substring(1, cleanValue.Length - 2);
}
// 解析为整数并添加到集合中
if (int.TryParse(cleanValue, out int num))
{
set2.Add(num);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error parsing second set: {ex.Message}");
return;
}
}
else
{
// 处理第二个集合以空格分隔的传统输入
string[] input2 = line2.Split(' ');
foreach (string num in input2)
{
if (int.TryParse(num, out int parsedNum))
{
set2.Add(parsedNum);
}
}
}
// 获取并集并输出结果
HashSet<int> unionSet = UnionSets(set1, set2);
Console.WriteLine(string.Join(" ", unionSet.OrderBy(x => x)));
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
逻辑与流程中的所有课
自己练习: C# 在线编译器