https://leetcode.com/problems/intersection-of-two-arrays-ii/
Please review for performance, I am having a problem with using TryGetValue, if someone can explain how this can be used in here.
Given two arrays, write a function to compute their intersection.
Example 1: Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2: Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note:Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ArrayQuestions
{
/// <summary>
/// https://leetcode.com/problems/intersection-of-two-arrays-ii/
/// </summary>
[TestClass]
public class IntersectionOfTwoArraysii
{
[TestMethod]
public void IntersectionOfDouble2Test()
{
int[] nums1 = {1, 2, 2, 1};
int[] nums2 = {2, 2};
CollectionAssert.AreEqual(nums2, Intersect(nums1,nums2));
}
public int[] Intersect(int[] nums1, int[] nums2)
{
if (nums1.Length > nums2.Length)
{
return Intersect(nums2, nums1);
}
Dictionary<int, int> nums1Count = new Dictionary<int, int>();
List<int> res = new List<int>();
foreach (var num in nums1)
{
if (!nums1Count.ContainsKey(num))
{
nums1Count.Add(num,1);
}
else
{
nums1Count[num]++;
}
}
foreach (var num in nums2)
{
if (nums1Count.ContainsKey(num) && nums1Count[num] > 0)
{
res.Add(num);
nums1Count[num]--;
}
}
return res.ToArray();
}
}
}