public class Solution
{
public int[] Intersect(int[] nums1, int[] nums2)
{
var len1 = nums1.Length;
var len2 = nums2.Length; var list = new List<int>();//用于存放最后的结果 var dic1 = new Dictionary<int, int>();//记录第一个数组的特征
var dic2 = new Dictionary<int, int>();//记录第二个数组的特征 for (int i = ; i < len1; i++)
{
if (!dic1.ContainsKey(nums1[i]))
{
dic1.Add(nums1[i], );
}
else
{
dic1[nums1[i]]++;
}
} for (int i = ; i < len2; i++)
{
if (!dic2.ContainsKey(nums2[i]))
{
dic2.Add(nums2[i], );
}
else
{
dic2[nums2[i]]++;
}
} if (dic1.Count <= dic2.Count)
{
//以dic1为基础循环 foreach (var d in dic1)
{
if (dic2.ContainsKey(d.Key))
{
var count = Math.Min(d.Value, dic2[d.Key]);
while (count > )
{
list.Add(d.Key);
count--;
}
}
}
}
else
{
//以dic2为基础循环
foreach (var d in dic2)
{
if (dic1.ContainsKey(d.Key))
{
var count = Math.Min(d.Value, dic1[d.Key]);
while (count > )
{
list.Add(d.Key);
count--;
}
}
}
} foreach (var l in list)
{
Console.WriteLine(l);
} return list.ToArray();
}
}

https://leetcode.com/problems/intersection-of-two-arrays-ii/#/description

04-25 23:13