LeetCode 0349. Intersection of Two Arrays Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0349. Intersection of Two Arrays

Description

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

Solutions

Solution 1: Hash Table or Array

First, we use a hash table or an array s of length 1001 to record the elements that appear in the array nums1. Then, we iterate through each element in the array nums2. If an element x is in s, we add x to the answer and remove x from s.

After the iteration is finished, we return the answer array.

The time complexity is O(n+m), and the space complexity is O(n). Here, n and m are the lengths of the arrays nums1 and nums2, respectively.

PythonJavaC++GoTypeScriptJavaScriptC#PHP
class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: return list(set(nums1) & set(nums2))(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !