Question
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.
Solution (Python)
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
len1 = len(nums1)
len2 = len(nums2)
smaller = nums1 if len1<=len2 else nums2
larger = nums1 if len1>len2 else nums2
#print(smaller)
final_list = []
for num in smaller:
try:
idx = larger.index(num)
larger.pop(idx)
final_list.append(num)
except ValueError:
pass
return final_list
Cracking the Coding Interview: 189 Programming Questions and Solutions