Пересечение двух массивов: решение на Python с использованием хеш-таблиц

Находите общие элементы двух массивов за O(n) с помощью хеш-сетов. Лаконичный Python-код с разбором логики шаг за шагом.

Бесплатная консультация юриста

+7 (800) 302-87-29

Реклама jurik.ru

fed

I need to find the intersection of two arrays and return the common elements.

I’ll use a hash set approach for efficient O(n) lookup:
Store all elements from the first array in a set
Iterate through the second array and check if each element exists in the set
Add matching elements to the result

def intersection(nums1: list[int], nums2: list[int]) -> list[int]:
# Use set for O(1) lookup
set1 = set(nums1)

# Find common elements
result = []
for num in nums2:
if num in set1:
result.append(num)
set1.remove(num) # Remove to avoid duplicates in result

return result

def intersection(nums1: list[int], nums2: list[int]) -> list[int]:
return list(set(nums1) & set(nums2))

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

Step 1: set1 = {1, 2}
Step 2: Check nums2 elements:
ー 2 ∈ set1? Yes → add to result, set1 = {1}
⎻ 2 ∈ set1? No (already removed)

Result: [2]

| Approach | Time | Space |
|———-|——|——-|
| Hash Set | O(n + m) | O(min(n, m)) |
| Set Intersection | O(n + m) | O(n + m) |

— First approach: Returns each common element once, preserves no specific order
— Second approach: Cleaner but also returns unique elements only
— If you need all duplicates (e.g., `[2,2]` if 2 appears twice in both), use a counter/hash map instead

from collections import Counter

def intersection_with_duplicates(nums1, nums2):
count1 = Counter(nums1)
result = []

for num in nums2:
if count1[num] > 0:
result.append(num)
count1[num] -= 1

return result

This returns `[2, 2]` for the example above.