求两个集合的交集和并集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


   结果如图:

 

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

 

转载于:https://www.cnblogs.com/gdouzz/p/4771487.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值