Leetcode 349 c# 用HashSet解题

本文介绍了一种使用C#实现的数组交集算法,通过将第一个数组存储在HashSet中,然后遍历第二个数组查找匹配项,并将结果转换为数组返回。提供了完整的代码示例,包括主函数和交集函数的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2019年1月28日

return nums1.Intersect(nums2).ToArray();

今天重新整理了博客 :

2018年12月17日

1 、第一个数组存到  HashSet 中

2、将第二个数组等于set的就加到一个集合里

3、将集合转为数组返回

 

        static void Main(string[] args)
        { 
            int[] oos = new int[] { 9, 4, 9, 8, 4 };
            int[] oop = new int[] { 9, 4 };
            int[]s= Intersection(oos, oop);
            for (int i = 0; i < s.Length; i++)
            {
                Console.WriteLine(s[i]);
            } 
            Console.ReadKey();
        }
        public static int[] Intersection(int[] nums1, int[] nums2)
        {
            HashSet<int> set = new HashSet<int>(); 
            for (int p = 0; p < nums1.Length; p++)
                 set.Add(nums1[p]);
            List<int> resultList = new List<int>();
            for (int z = 0; z < nums2.Length; z++)
            {
                if (set.Contains(nums2[z]))
                {
                    resultList.Add(nums2[z]);
                    set.Remove(nums2[z]);
                } 
            }
            int[] num = new int[resultList.Count] ;
            if (num.Count() <= 0)
                return num;
            for (int i = 0; i < resultList.Count; i++)
            {
                num[i] = resultList[i];
            }
            return num;
        }

请参考我2019年1/30新写的方法https://blog.youkuaiyun.com/us2019/article/details/80538723

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值