HomeLeetcode350. Intersection of Two Arrays II - Leetcode Solutions

350. Intersection of Two Arrays II – Leetcode Solutions

Description:

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.

Examples:

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.

Solution in Python:

To solve the problem of finding the intersection of two integer arrays where each element in the result appears as many times as it shows in both arrays, we can use a hashmap (dictionary) to count the occurrences of each element in one of the arrays. Then, we iterate through the other array to determine how many times each element should appear in the result based on the counts in the hashmap.

Python
from typing import List

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Dictionary to count occurrences in nums1
        counts = {}
        
        # Fill the dictionary with counts of each element in nums1
        for num in nums1:
            if num in counts:
                counts[num] += 1
            else:
                counts[num] = 1
        
        # List to store the result
        result = []
        
        # Check each element in nums2 against the dictionary
        for num in nums2:
            if num in counts and counts[num] > 0:
                result.append(num)
                counts[num] -= 1
        
        return result

# Example usage:
# Create an instance of the Solution class
solution = Solution()

# Example 1
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
print(solution.intersect(nums1, nums2))  # Output: [2, 2]

# Example 2
nums1 = [4, 9, 5]
nums2 = [9, 4, 9, 8, 4]
print(solution.intersect(nums1, nums2))  # Output: [4, 9]

Explanation of the Code:

  • Line 1: We import List from typing to specify the type of the input lists.
  • Line 3-5: We define the Solution class and the intersect method which takes two lists nums1 and nums2 as inputs and returns a list of their intersection.
  • Line 7-11: We create a dictionary counts to store the counts of each element in nums1.
  • Line 9-11: We iterate over nums1 and update the dictionary with the count of each element.
  • Line 14: We initialize an empty list result to store the intersection result.
  • Line 17-21: We iterate over nums2 and for each element, check if it is in the dictionary and its count is greater than zero. If so, we append the element to result and decrease the count in the dictionary.
  • Line 23: We return the result list containing the intersection elements with the correct counts.

The provided example usages demonstrate how to use the Solution class and the intersect method to get the intersection of two arrays.

Solution in Javascript:

JavaScript
/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function(nums1, nums2) {
    // Object to count occurrences in nums1
    const counts = {};
    
    // Fill the object with counts of each element in nums1
    for (let num of nums1) {
        if (counts[num] !== undefined) {
            counts[num]++;
        } else {
            counts[num] = 1;
        }
    }
    
    // Array to store the result
    const result = [];
    
    // Check each element in nums2 against the object
    for (let num of nums2) {
        if (counts[num] > 0) {
            result.push(num);
            counts[num]--;
        }
    }
    
    return result;
};

// Example usage:
// Example 1
let nums1 = [1, 2, 2, 1];
let nums2 = [2, 2];
console.log(intersect(nums1, nums2)); // Output: [2, 2]

// Example 2
nums1 = [4, 9, 5];
nums2 = [9, 4, 9, 8, 4];
console.log(intersect(nums1, nums2)); // Output: [4, 9]

Solution in Java:

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;

class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        // HashMap to count occurrences in nums1
        HashMap<Integer, Integer> counts = new HashMap<>();
        
        // Fill the HashMap with counts of each element in nums1
        for (int num : nums1) {
            counts.put(num, counts.getOrDefault(num, 0) + 1);
        }
        
        // List to store the result
        List<Integer> result = new ArrayList<>();
        
        // Check each element in nums2 against the HashMap
        for (int num : nums2) {
            if (counts.containsKey(num) && counts.get(num) > 0) {
                result.add(num);
                counts.put(num, counts.get(num) - 1);
            }
        }
        
        // Convert the result list to an array
        int[] resultArray = new int[result.size()];
        for (int i = 0; i < result.size(); i++) {
            resultArray[i] = result.get(i);
        }
        
        return resultArray;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        
        // Example 1
        int[] nums1Example1 = {1, 2, 2, 1};
        int[] nums2Example1 = {2, 2};
        int[] result1 = solution.intersect(nums1Example1, nums2Example1);
        System.out.println(Arrays.toString(result1)); // Output: [2, 2]

        // Example 2
        int[] nums1Example2 = {4, 9, 5};
        int[] nums2Example2 = {9, 4, 9, 8, 4};
        int[] result2 = solution.intersect(nums1Example2, nums2Example2);
        System.out.println(Arrays.toString(result2)); // Output: [4, 9]
    }
}

Solution in C#:

C#
using System;
using System.Collections.Generic;

public class Solution {
    public int[] Intersect(int[] nums1, int[] nums2) {
        // Dictionary to count occurrences in nums1
        Dictionary<int, int> counts = new Dictionary<int, int>();
        
        // Fill the dictionary with counts of each element in nums1
        foreach (int num in nums1) {
            if (counts.ContainsKey(num)) {
                counts[num]++;
            } else {
                counts.Add(num, 1);
            }
        }
        
        // List to store the result
        List<int> result = new List<int>();
        
        // Check each element in nums2 against the dictionary
        foreach (int num in nums2) {
            if (counts.ContainsKey(num) && counts[num] > 0) {
                result.Add(num);
                counts[num]--;
            }
        }
        
        // Convert the result list to an array
        return result.ToArray();
    }

}

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular