4
\$\begingroup\$

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();
 }
 }
}
asked Jun 13, 2019 at 20:26
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
 if (!nums1Count.ContainsKey(num))
 {
 nums1Count.Add(num,1);
 }
 else
 {
 nums1Count[num]++;
 }

I think it can be written as:

nums1Count.TryGetValue(num, out int count);
nums1Count[num] = count + 1;

You don't have to test the return value of TryGetValue() in this case, because TryGetValue() sets count to default (0) if it returns false.

The loop could also be written as a LINQ sequence as:

var nums1Count = data.GroupBy(i => i).ToDictionary(gr => gr.Key, gr => gr.Count());

Likewise:

 if (nums1Count.ContainsKey(num) && nums1Count[num] > 0)
 {
 res.Add(num);
 nums1Count[num]--;
 }

can be changed to:

if (nums1Count.TryGetValue(num, out int count) && count > 0)
{
 res.Add(num);
 nums1Count[num]--;
}
answered Jun 14, 2019 at 4:03
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.