【力扣】两个数组的交集

两种情况 一种带重复数字 一种不带重复数字

不带重复数字

 

 

使用hashset 添加nums1自动去重  遍历nums2看在hashset中是否存在
再用一个hashset保存结果
 public int[] Intersection(int[] nums1, int[] nums2) {
            HashSet<int> nums = new HashSet<int>();
            HashSet<int> result = new HashSet<int>();
            for(int i = 0; i < nums1.Length; i++)
            {
                nums.Add(nums1[i]);
            }
            for(int i = 0; i < nums2.Length; i++)
            {
                if (nums.Contains(nums2[i]))
                {
                    result.Add(nums2[i]);
                    nums.Remove(nums2[i]);
                }
            }
            return result.ToArray();
        

    }

带重复数字

 

 两种方法 

第一种方法和上面类似, 使用Dictionary,key值为nums1的值,value为元素的个数

遍历nums2,如果在dictionary中有且个数大于0,存到result里,个数减一

public int[] Intersect(int[] nums1,int[] nums2)
        {
            if (nums1 == null || nums2 == null || nums1.Length == 0 || nums2.Length == 0)
            {
                return new int[] { };
            }
            //调整nums1为小数组
            if (nums1.Length > nums2.Length)
            {
                int[] temp = nums1;
                nums1 = nums2;
                nums2 = temp;
            }
            for (int i = 0; i < nums1.Length; i++)
            {
                Console.WriteLine(nums1[i]);
                Console.WriteLine("=");
            }
            for (int i = 0; i < nums2.Length; i++)
            {
                Console.WriteLine(nums2[i]);
                Console.WriteLine("-");
            }

            Dictionary<int, int> dic = new Dictionary<int, int>();
            for(int i = 0; i < nums1.Length; i++)
            {
                if (dic.ContainsKey(nums1[i]))
                {
                    dic[nums1[i]]++;
                }
                else
                {
                    dic.Add(nums2[i], 0);
                }
            }
            List<int> result= new List<int>();
            for(int i = 0; i < nums2.Length; i++)
            {
                if (dic.ContainsKey(nums2[i]) && dic[nums2[i]] >= 0)
                {
                    result.Add(nums2[i]);
                    dic[nums2[i]]--;
                }
               
            }
            return result.ToArray();
           

        }

第二种方法 排序 双指针法

i指向nums1 j指向nums2

        Array.Sort(nums1);
            Array.Sort(nums2);
            int i = 0, j = 0;
            List<int> result = new List<int>();
            while (i < nums1.Length && j < nums2.Length)
            {
                if (nums1[i] < nums2[j])
                {
                    i++;
                }
                else if(nums1[i]>nums2[j])
                {
                    j++;
                }
                else
                {
                    result.Add(nums1[i]);
                    i++;
                    j++;
                }
            }
            return result.ToArray();

 

posted @ 2020-03-26 17:39  An_Wen  阅读(221)  评论(0编辑  收藏  举报