Arrays Intersection
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
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]
Explanation: [9,4] is also accepted.Constraints:
1 <= nums1.length, nums2.length <= 10000 <= nums1[i], nums2[i] <= 1000
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if num1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Solutions
Approach - Brute Force Technique
It works by checking each element of the first array against the second array and adding it to the intersection if it exists. The second array is represented as a list so that elements can be easily removed. This ensures that each element is counted the correct number of times.
Steps
Initialize intersection and list2: A new List
intersectionis created to store the intersection ofnums1andnums2. Another Listlist2is created as a copy ofnums2. This is done because elements will be removed fromlist2during the process, and we don’t want to modify the original array.Iterate over nums1: The method iterates over each element
numinnums1.Check if num exists in list2: For each
numinnums1, the method checks ifnumexists inlist2using theContainsmethod.Add num to intersection and remove from list2: If
numexists inlist2, it is added tointersectionand removed fromlist2. TheRemovemethod removes the first occurrence ofnumfromlist2. This ensures that each element in the intersection appears as many times as it shows in both arrays.Return intersection as an array: After all elements in
nums1have been processed, theToArraymethod is called onintersectionto convert it back to an array before returning it as the result of the method.
public class Solution
{
public int[] Intersect(int[] nums1, int[] nums2)
{
List<int> intersection = new List<int>();
List<int> list2 = new List<int>(nums2);
foreach (int num in nums1)
{
if (list2.Contains(num))
{
intersection.Add(num);
list2.Remove(num);
}
}
return intersection.ToArray();
}
}Approach - Hash Table Technique
Steps
Initialization: The function
Intersectis defined with two parameters,nums1andnums2, which are the input arrays. It initializes a dictionarydictto keep track of the frequency of each number innums1, and a listresto store the result.Create Frequency Dictionary: The function iterates over each number in
nums1. For each number, it checks if the number is already a key indict. If it is, it increments the value associated with that key. If not, it adds the number as a key todictwith a value of 1. This results indictcontaining each unique number innums1as a key, and the frequency of that number as the value.Find Intersection: The function then iterates over each number in
nums2. For each number, it checks if the number is a key indictand if the associated value is greater than 0. If both conditions are met, it means the number is present in bothnums1andnums2, so it adds the number toresand decrements the value associated with the number indict.Return Result: Finally, the function converts
resto an array and returns it. This array contains the intersection ofnums1andnums2.
public class Solution {
public int[] Intersect(int[] nums1, int[] nums2) {
var dict = new Dictionary<int, int>();
var res = new List<int>();
foreach (var num in nums1)
{
if (dict.ContainsKey(num))
dict[num]++;
else
dict[num] = 1;
}
foreach (var num in nums2)
{
if (dict.ContainsKey(num) && dict[num]>0)
{
res.Add(num);
dict[num]--;
}
}
return res.ToArray();
}
}Complexity
Time complexity:
O(N+M)Space complexity:
O(N)
Last updated