| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.IntersectionOfTwoArrays2; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class IntersectionOfTwoArrays2Dictionary : IIntersectionOfTwoArrays2 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n + m) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums1"></param> |
| | 22 | | /// <param name="nums2"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int[] Intersect(int[] nums1, int[] nums2) |
| 2 | 25 | | { |
| 2 | 26 | | var nums1Dictionary = new Dictionary<int, int>(); |
| | 27 | |
|
| 20 | 28 | | foreach (var num1 in nums1) |
| 7 | 29 | | { |
| 7 | 30 | | if (!nums1Dictionary.TryAdd(num1, 1)) |
| 2 | 31 | | { |
| 2 | 32 | | nums1Dictionary[num1]++; |
| 2 | 33 | | } |
| 7 | 34 | | } |
| | 35 | |
|
| 2 | 36 | | var result = new List<int>(); |
| | 37 | |
|
| 20 | 38 | | foreach (var num2 in nums2) |
| 7 | 39 | | { |
| 7 | 40 | | if (!nums1Dictionary.ContainsKey(num2)) |
| 3 | 41 | | { |
| 3 | 42 | | continue; |
| | 43 | | } |
| | 44 | |
|
| 4 | 45 | | result.Add(num2); |
| | 46 | |
|
| 4 | 47 | | nums1Dictionary[num2]--; |
| | 48 | |
|
| 4 | 49 | | if (nums1Dictionary[num2] == 0) |
| 3 | 50 | | { |
| 3 | 51 | | nums1Dictionary.Remove(num2); |
| 3 | 52 | | } |
| 4 | 53 | | } |
| | 54 | |
|
| 2 | 55 | | return [.. result]; |
| 2 | 56 | | } |
| | 57 | | } |