• 求两个集合的交集和并集C#


        我是用hashset<T>来实现的 具体如代码所示

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace JiaoJi
    {
        class Program
        {
            static void Main(string[] args)
            {
                int [] arrA=new int[8]{1,2,3,4,5,6,7,8};
                 int [] arrB=new int[5]{4,5,6,7,8};
                HashSet<int> hashset=new HashSet<int>();
                hashset = JiaoJi(arrA, arrB);
                HashSet<int> hashsetB = new HashSet<int>();
                hashsetB = BingJi(arrA, arrB);
                Console.Write("他们交集如下:");
                foreach (var i in hashset)
                {
                    Console.Write(i);
                }
                Console.WriteLine();
                Console.Write("他们的并集如下:");
                foreach (var i in hashsetB)
                {
                    Console.Write(i);
                }
                Console.ReadKey();
               
            }
            /// <summary>
            /// 求两个数组的并集
            /// </summary>
            /// <param name="arrayA"></param>
            /// <param name="arrayB"></param>
            /// <returns></returns>
            static HashSet<int> BingJi(int[] arrayA, int[] arrayB)
            {
                HashSet<int> hashset = new HashSet<int>();
                for (int i = 0; i < arrayA.Length; i++)
                {
                    hashset.Add(arrayA[i]);
                }
                for (int j = 0; j < arrayB.Length; j++)
                {
                    hashset.Add(arrayB[j]);
    
                }
                return hashset;
    
            }
            /// <summary>
            /// 求两个集合的交集 
            /// </summary>
            /// <param name="arrayA">传入数组a</param>
            /// <param name="arrayB">传入数组B</param>
            /// <returns></returns>
            static HashSet<int> JiaoJi(int[] arrayA, int[] arrayB)
            {
                //求两个集合的交集  //hashset的就是专门求两个交集而生的  或者并集 他的add方法的 会判断
                //如果你存在了这个记录,他就会返回false 这里就是利用了这个思路
                HashSet<int> s = new HashSet<int>();
                HashSet<int> s2 = new HashSet<int>();
                for (int i = 0; i < arrayA.Length; i++)
                {
                    s.Add(arrayA[i]);
                }
                for (int j = 0; j < arrayB.Length; j++)
                {
                    if (s.Add(arrayB[j]) == false)
                    {
                        s2.Add(arrayB[j]);
                    }
                }
                return s2;
            }
        }
    }
    View Code


       结果如图:

      如果有什么疑问,欢迎大家一起讨论学习

  • 相关阅读:
    99乘法表的几种实现方法
    log4net使用(包括单个文件和按日期生成多个文件)
    c# 压缩文件
    寻找Windows下MySQL的错误日志
    MySQL 索引
    java hashCode 作用
    springMVC swagger2
    ConcurrentHashMap原理分析(1.7与1.8)
    国产烂片深度揭秘
    Practice| 类型转换| 逻辑运算
  • 原文地址:https://www.cnblogs.com/gdouzz/p/4771487.html
Copyright © 2020-2023  润新知