Skip to content

Latest commit

 

History

History
110 lines (74 loc) · 2.13 KB

349.intersection-of-two-arrays.en.md

File metadata and controls

110 lines (74 loc) · 2.13 KB

Problem (349. Intersection of two arrays)

https://leetcode.com/problems/intersection-of-two-arrays/

Title description

Given two arrays, write a function to calculate their intersection.



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]


description:

Each element in the output must be unique.
We can not consider the order of the output results.

Pre-knowledge

  • hashtable

Company

-Ali -Tencent -Baidu -Byte

Idea

First traverse the first array, store it in the hashtable, and then traverse the second array. If it exists in the hashtable, push it to ret, then empty the hashtable, and finally return to ret.

Analysis of key points

-Space for time

Code

Code support: JS, Python

Javascript Code:

/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number[]}
*/
var intersection = function (nums1, nums2) {
const visited = {};
const ret = [];
for (let i = 0; i < nums1. length; i++) {
const num = nums1[i];

visited[num] = num;
}

for (let i = 0; i < nums2. length; i++) {
const num = nums2[i];

if (visited[num] ! == undefined) {
ret. push(num);
visited[num] = undefined;
}
}

return ret;
};

Python Code:

class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
visited, result = {}, []
for num in nums1:
visited[num] = num
for num in nums2:
if num in visited:
result. append(num)
visited. pop(num)
return result

# Another solution: Use collections in Python to calculate
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
return set(nums1) & set(nums2)

Complexity analysis

-Time complexity:$O(N)$ -Spatial complexity:$O(N)$

For more questions, please visit my LeetCode questions warehouse:https://github.com/azl397985856/leetcode . There are already 37K stars.

Pay attention to the official account, work hard to restore the problem-solving ideas in clear and straightforward language, and there are a large number of diagrams to teach you how to recognize routines and brush questions efficiently.