Menu
CoddyTech

数学:HashSet 的交集

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 63 课,共 66 课。

两个集合的交集只包含同时出现在这两个集合中的元素。

创建两个 HashSet:

HashSet<int> set1 = new HashSet<int>() { 1, 2, 3, 4, 5 };
HashSet<int> set2 = new HashSet<int>() { 3, 4, 5, 6, 7 };

要查找交集,请使用 IntersectWith 方法:

set1.IntersectWith(set2);

运行这段代码后,set1 将包含:

{ 3, 4, 5 }

IntersectWith 方法会修改调用它的集合,只保留两个集合中都存在的元素。

要创建一个包含交集的新集合,同时不修改原集合,你可以这样做:

HashSet<int> intersection = new HashSet<int>(set1);
intersection.IntersectWith(set2);
challenge icon

挑战

中等

创建一个名为 FindCommonElements 的方法,它接受两个参数:

  • 一个整数 HashSet(set1)
  • 一个整数 HashSet(set2)

该方法应返回一个新的 HashSet,其中只包含同时出现在两个集合中的元素(交集)。

亲手试试

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program {
    public static HashSet<int> FindCommonElements(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 s in input1) {
                if (int.TryParse(s, out int num)) {
                    set1.Add(num);
                }
            }
        }
        
        // 读取第二行,作为第二个集合
        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 s in input2) {
                if (int.TryParse(s, out int num)) {
                    set2.Add(num);
                }
            }
        }
        
        // 找出共同元素
        HashSet<int> common = FindCommonElements(set1, set2);
        
        // 输出结果(已排序)
        Console.WriteLine(string.Join(" ", common.OrderBy(x => x)));
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器