Skip to content

Commit 5164054

Browse files
committed
intersection of arrays
1 parent d15924c commit 5164054

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"Leetcode- https://leetcode.com/problems/intersection-of-two-arrays/ "
2+
'''
3+
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.
4+
5+
Example 1:
6+
7+
Input: nums1 = [1,2,2,1], nums2 = [2,2]
8+
Output: [2]
9+
'''
10+
11+
12+
def intersection(self, nums1, nums2):
13+
nums1.sort()
14+
nums2.sort()
15+
16+
i = 0
17+
j = 0
18+
res = []
19+
while i < len(nums1) and j < len(nums2):
20+
if i > 0 and nums1[i] == nums1[i-1]:
21+
i += 1
22+
continue
23+
if nums1[i] < nums2[j]:
24+
i += 1
25+
elif nums1[i] > nums2[j]:
26+
j += 1
27+
else:
28+
res.append(nums1[i])
29+
i += 1
30+
j += 1
31+
return res
32+
33+
# T:O(N)
34+
# S:O(N)
35+
36+
37+
def intersection(self, nums1, nums2):
38+
set1 = set(nums1)
39+
set2 = set(nums2)
40+
41+
return list(set2 & set1)
42+
# T:O(N+M)
43+
# S:O(N+M)

0 commit comments

Comments
 (0)