forked from super30admin/Array-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInterSection2.py
More file actions
56 lines (45 loc) · 1.29 KB
/
InterSection2.py
File metadata and controls
56 lines (45 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
Given two integer arrays nums1 and nums2,
return an array of their intersection.
Each element in the result must appear as many times as it shows in both arrays and you may return
the result in any order.
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
"""
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
"""
TC onlogn, m+logn
sc -1
"""
nums1.sort()
nums2.sort()
i, j = 0, 0
result = []
while i < len(nums1) and j < len(nums2):
if nums1[i] > nums2[j]:
j += 1
elif nums1[i] < nums2[j]:
i += 1
else:
result.append(nums1[i])
i += 1
j += 1
return result
"""
Time: O(m+n), space- o(min(m,n))
"""
if len(nums2) < len(nums1):
return self.intersect(nums2, nums1)
hashmap = {} ##put smaller length in hashmap
result = []
for c in nums1:
if c in hashmap:
hashmap[c] += 1
else:
hashmap[c] = 1
for c in nums2:
if c in hashmap and hashmap[c] > 0:
result.append(c)
hashmap[c] -= 1
return result