Algorithm


Problem Name: 349. Intersection of Two Arrays

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

 

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

 

Constraints:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Code Examples

#1 Code Example with C Programming

Code - C Programming


class Solution {
  public int[] intersection(int[] nums1, int[] nums2) {
    boolean[][] found = new boolean[1001][2];
    for (int num : nums1) {
      found[num][0] = true;
    }
    int count = 0;
    for (int num : nums2) {
      if (!found[num][1]) {
        if (found[num][0]) {
          count++;
        }
      }
      found[num][1] = true;
    }
    int[] result = new int[count];
    int idx = 0;
    for (int i = 1; i  < = 1000; i++) {
      if (found[i][0] && found[i][1]) {
        result[idx++] = i;
      }
    }
    return result;
  }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums1 = [1,2,2,1], nums2 = [2,2]

Output

x
+
cmd
[2]

#2 Code Example with Javascript Programming

Code - Javascript Programming


const intersection = function(nums1, nums2) {
  const obj = {};
  nums1.forEach(i => (obj[i] = true));

  return nums2.filter(j => {
    if (obj[j]) {
      delete obj[j];
      return true;
    }
    return false;
  });
};
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums1 = [1,2,2,1], nums2 = [2,2]

Output

x
+
cmd
[2]

#3 Code Example with Python Programming

Code - Python Programming


class Solution:
    def intersection(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        return list(set(nums1)&set(nums2))
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output

x
+
cmd
[9,4]

#4 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;

namespace LeetCode
{
    public class _0349_IntersectionOfTwoArrays
    {
        public int[] Intersection(int[] nums1, int[] nums2)
        {
            var set1 = new HashSet < int>(nums1);
            var set2 = new HashSet<int>(nums2);

            var result = new List < int>();
            foreach (var num in set1)
                if (set2.Contains(num)) result.Add(num);

            return result.ToArray();
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums1 = [4,9,5], nums2 = [9,4,9,8,4]

Output

x
+
cmd
[9,4]
Advertisements

Demonstration


Previous
#347 Leetcode Top K Frequent Elements Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#350 Leetcode Intersection of Two Arrays II Solution in C, C++, Java, JavaScript, Python, C# Leetcode